1
0

main.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. #include "ggml.h"
  2. #include "utils.h"
  3. #include <cassert>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <fstream>
  8. #include <map>
  9. #include <string>
  10. #include <vector>
  11. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  12. #include <signal.h>
  13. #include <unistd.h>
  14. #elif defined (_WIN32)
  15. #include <signal.h>
  16. #endif
  17. #define ANSI_COLOR_RED "\x1b[31m"
  18. #define ANSI_COLOR_GREEN "\x1b[32m"
  19. #define ANSI_COLOR_YELLOW "\x1b[33m"
  20. #define ANSI_COLOR_BLUE "\x1b[34m"
  21. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  22. #define ANSI_COLOR_CYAN "\x1b[36m"
  23. #define ANSI_COLOR_RESET "\x1b[0m"
  24. #define ANSI_BOLD "\x1b[1m"
  25. // determine number of model parts based on the dimension
  26. static const std::map<int, int> LLAMA_N_PARTS = {
  27. { 4096, 1 },
  28. { 5120, 2 },
  29. { 6656, 4 },
  30. { 8192, 8 },
  31. };
  32. // default hparams (LLaMA 7B)
  33. struct llama_hparams {
  34. int32_t n_vocab = 32000;
  35. int32_t n_ctx = 512; // this is provided as user input?
  36. int32_t n_embd = 4096;
  37. int32_t n_mult = 256;
  38. int32_t n_head = 32;
  39. int32_t n_layer = 32;
  40. int32_t n_rot = 64;
  41. int32_t f16 = 1;
  42. };
  43. struct llama_layer {
  44. // normalization
  45. struct ggml_tensor * attention_norm;
  46. // attention
  47. struct ggml_tensor * wq;
  48. struct ggml_tensor * wk;
  49. struct ggml_tensor * wv;
  50. struct ggml_tensor * wo;
  51. // normalization
  52. struct ggml_tensor * ffn_norm;
  53. // ff
  54. struct ggml_tensor * w1;
  55. struct ggml_tensor * w2;
  56. struct ggml_tensor * w3;
  57. };
  58. struct llama_model {
  59. llama_hparams hparams;
  60. struct ggml_tensor * tok_embeddings;
  61. struct ggml_tensor * norm;
  62. struct ggml_tensor * output;
  63. std::vector<llama_layer> layers;
  64. // key + value memory
  65. struct ggml_tensor * memory_k;
  66. struct ggml_tensor * memory_v;
  67. //
  68. struct ggml_context * ctx;
  69. std::map<std::string, struct ggml_tensor *> tensors;
  70. };
  71. // load the model's weights from a file
  72. bool llama_model_load(const std::string & fname, llama_model & model, gpt_vocab & vocab, int n_ctx, ggml_type memory_type = GGML_TYPE_F32) {
  73. fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  74. std::vector<char> f_buf(1024*1024);
  75. auto fin = std::ifstream(fname, std::ios::binary);
  76. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  77. if (!fin) {
  78. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  79. return false;
  80. }
  81. // verify magic
  82. {
  83. uint32_t magic;
  84. fin.read((char *) &magic, sizeof(magic));
  85. if (magic != 0x67676d6c) {
  86. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  87. return false;
  88. }
  89. }
  90. int n_ff = 0;
  91. int n_parts = 0;
  92. // load hparams
  93. {
  94. auto & hparams = model.hparams;
  95. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  96. //fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  97. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  98. fin.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  99. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  100. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  101. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  102. fin.read((char *) &hparams.f16, sizeof(hparams.f16));
  103. hparams.n_ctx = n_ctx;
  104. n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  105. n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
  106. fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  107. fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  108. fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
  109. fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
  110. fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
  111. fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
  112. fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
  113. fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
  114. fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
  115. fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
  116. }
  117. // load vocab
  118. {
  119. std::string word;
  120. for (int i = 0; i < model.hparams.n_vocab; i++) {
  121. uint32_t len;
  122. fin.read((char *) &len, sizeof(len));
  123. word.resize(len);
  124. fin.read((char *) word.data(), len);
  125. vocab.token_to_id[word] = i;
  126. vocab.id_to_token[i] = word;
  127. //if (i < 30000) {
  128. // fprintf(stderr, "%s: vocab[%d] = '%s'\n", __func__, i, word.c_str());
  129. //}
  130. }
  131. }
  132. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  133. // in order to save memory and also to speed up the computation
  134. ggml_type wtype = GGML_TYPE_COUNT;
  135. switch (model.hparams.f16) {
  136. case 0: wtype = GGML_TYPE_F32; break;
  137. case 1: wtype = GGML_TYPE_F16; break;
  138. case 2: wtype = GGML_TYPE_Q4_0; break;
  139. case 3: wtype = GGML_TYPE_Q4_1; break;
  140. default:
  141. {
  142. fprintf(stderr, "%s: invalid model file '%s' (bad f16 value %d)\n",
  143. __func__, fname.c_str(), model.hparams.f16);
  144. return false;
  145. }
  146. }
  147. auto & ctx = model.ctx;
  148. size_t ctx_size = 0;
  149. {
  150. const auto & hparams = model.hparams;
  151. const int n_embd = hparams.n_embd;
  152. const int n_layer = hparams.n_layer;
  153. const int n_ctx = hparams.n_ctx;
  154. const int n_vocab = hparams.n_vocab;
  155. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // tok_embeddings
  156. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // norm
  157. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // output
  158. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // attention_norm
  159. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wq
  160. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wk
  161. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wv
  162. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wo
  163. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ffn_norm
  164. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w1
  165. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w2
  166. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w3
  167. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_k
  168. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_v
  169. ctx_size += (5 + 10*n_layer)*256; // object overhead
  170. fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  171. }
  172. // create the ggml context
  173. {
  174. struct ggml_init_params params = {
  175. /*.mem_size =*/ ctx_size,
  176. /*.mem_buffer =*/ NULL,
  177. };
  178. model.ctx = ggml_init(params);
  179. if (!model.ctx) {
  180. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  181. return false;
  182. }
  183. }
  184. // prepare memory for the weights
  185. {
  186. const auto & hparams = model.hparams;
  187. const int n_embd = hparams.n_embd;
  188. const int n_layer = hparams.n_layer;
  189. const int n_vocab = hparams.n_vocab;
  190. model.layers.resize(n_layer);
  191. model.tok_embeddings = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  192. model.norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  193. model.output = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  194. // map by name
  195. model.tensors["tok_embeddings.weight"] = model.tok_embeddings;
  196. model.tensors["norm.weight"] = model.norm;
  197. model.tensors["output.weight"] = model.output;
  198. for (int i = 0; i < n_layer; ++i) {
  199. auto & layer = model.layers[i];
  200. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  201. layer.wq = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  202. layer.wk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  203. layer.wv = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  204. layer.wo = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  205. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  206. layer.w1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  207. layer.w2 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd);
  208. layer.w3 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  209. // map by name
  210. model.tensors["layers." + std::to_string(i) + ".attention_norm.weight"] = layer.attention_norm;
  211. model.tensors["layers." + std::to_string(i) + ".attention.wq.weight"] = layer.wq;
  212. model.tensors["layers." + std::to_string(i) + ".attention.wk.weight"] = layer.wk;
  213. model.tensors["layers." + std::to_string(i) + ".attention.wv.weight"] = layer.wv;
  214. model.tensors["layers." + std::to_string(i) + ".attention.wo.weight"] = layer.wo;
  215. model.tensors["layers." + std::to_string(i) + ".ffn_norm.weight"] = layer.ffn_norm;
  216. model.tensors["layers." + std::to_string(i) + ".feed_forward.w1.weight"] = layer.w1;
  217. model.tensors["layers." + std::to_string(i) + ".feed_forward.w2.weight"] = layer.w2;
  218. model.tensors["layers." + std::to_string(i) + ".feed_forward.w3.weight"] = layer.w3;
  219. }
  220. }
  221. // key + value memory
  222. {
  223. const auto & hparams = model.hparams;
  224. const int n_embd = hparams.n_embd;
  225. const int n_layer = hparams.n_layer;
  226. const int n_ctx = hparams.n_ctx;
  227. const int n_mem = n_layer*n_ctx;
  228. const int n_elements = n_embd*n_mem;
  229. model.memory_k = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  230. model.memory_v = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  231. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  232. fprintf(stderr, "%s: memory_size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  233. }
  234. const size_t file_offset = fin.tellg();
  235. fin.close();
  236. std::vector<uint8_t> tmp;
  237. for (int i = 0; i < n_parts; ++i) {
  238. const int part_id = i;
  239. //const int part_id = n_parts - i - 1;
  240. std::string fname_part = fname;
  241. if (i > 0) {
  242. fname_part += "." + std::to_string(i);
  243. }
  244. fprintf(stderr, "%s: loading model part %d/%d from '%s'\n", __func__, i+1, n_parts, fname_part.c_str());
  245. fin = std::ifstream(fname_part, std::ios::binary);
  246. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  247. fin.seekg(file_offset);
  248. // load weights
  249. {
  250. int n_tensors = 0;
  251. size_t total_size = 0;
  252. fprintf(stderr, "%s: ", __func__);
  253. while (true) {
  254. int32_t n_dims;
  255. int32_t length;
  256. int32_t ftype;
  257. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  258. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  259. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  260. if (fin.eof()) {
  261. break;
  262. }
  263. int32_t nelements = 1;
  264. int32_t ne[2] = { 1, 1 };
  265. for (int i = 0; i < n_dims; ++i) {
  266. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  267. nelements *= ne[i];
  268. }
  269. std::string name(length, 0);
  270. fin.read(&name[0], length);
  271. if (model.tensors.find(name.data()) == model.tensors.end()) {
  272. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
  273. return false;
  274. }
  275. // split_type = 0: split by columns
  276. // split_type = 1: split by rows
  277. int split_type = 0;
  278. // split_type = 0:
  279. // regex:
  280. // - tok_embeddings.*
  281. // - layers.*.attention.wo.weight
  282. // - layers.*.feed_forward.w2.weight
  283. // split_type = 1:
  284. // regex:
  285. // - output.*
  286. // - layers.*.attention.wq.weight
  287. // - layers.*.attention.wk.weight
  288. // - layers.*.attention.wv.weight
  289. // - layers.*.feed_forward.w1.weight
  290. // - layers.*.feed_forward.w3.weight
  291. if (name.find("tok_embeddings") != std::string::npos) {
  292. split_type = 0;
  293. } else if (name.find("layers") != std::string::npos) {
  294. if (name.find("attention.wo.weight") != std::string::npos) {
  295. split_type = 0;
  296. } else if (name.find("feed_forward.w2.weight") != std::string::npos) {
  297. split_type = 0;
  298. } else {
  299. split_type = 1;
  300. }
  301. } else if (name.find("output") != std::string::npos) {
  302. split_type = 1;
  303. }
  304. auto tensor = model.tensors[name.data()];
  305. if (n_dims == 1) {
  306. if (ggml_nelements(tensor) != nelements) {
  307. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  308. return false;
  309. }
  310. } else {
  311. if (ggml_nelements(tensor)/n_parts != nelements) {
  312. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  313. return false;
  314. }
  315. }
  316. if (n_dims == 1) {
  317. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  318. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  319. __func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
  320. return false;
  321. }
  322. } else {
  323. if (split_type == 0) {
  324. if (tensor->ne[0]/n_parts != ne[0] || tensor->ne[1] != ne[1]) {
  325. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  326. __func__, name.data(), tensor->ne[0]/n_parts, tensor->ne[1], ne[0], ne[1]);
  327. return false;
  328. }
  329. } else {
  330. if (tensor->ne[0] != ne[0] || tensor->ne[1]/n_parts != ne[1]) {
  331. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  332. __func__, name.data(), tensor->ne[0], tensor->ne[1]/n_parts, ne[0], ne[1]);
  333. return false;
  334. }
  335. }
  336. }
  337. if (0) {
  338. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  339. fprintf(stderr, "%24s - [%5d, %5d], type = %6s, split = %d\n", name.data(), ne[0], ne[1], ftype_str[ftype], split_type);
  340. }
  341. size_t bpe = 0;
  342. switch (ftype) {
  343. case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
  344. case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
  345. case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
  346. case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
  347. default:
  348. {
  349. fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
  350. return false;
  351. }
  352. };
  353. if (n_dims == 1 || n_parts == 1) {
  354. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  355. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  356. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  357. return false;
  358. }
  359. if (part_id == 0) {
  360. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  361. } else {
  362. fin.seekg(ggml_nbytes(tensor), std::ios::cur);
  363. }
  364. total_size += ggml_nbytes(tensor);
  365. } else {
  366. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)/n_parts) {
  367. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  368. __func__, name.data(), ggml_nbytes(tensor)/n_parts, nelements*bpe);
  369. return false;
  370. }
  371. if (split_type == 0) {
  372. const int np0 = ne[0];
  373. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  374. assert(row_size == tensor->nb[1]);
  375. for (int i1 = 0; i1 < ne[1]; ++i1) {
  376. const size_t offset_row = i1*row_size;
  377. const size_t offset = offset_row + ((part_id*np0)/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  378. fin.read(reinterpret_cast<char *>(tensor->data) + offset, row_size/n_parts);
  379. }
  380. } else {
  381. const int np1 = ne[1];
  382. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  383. for (int i1 = 0; i1 < ne[1]; ++i1) {
  384. const size_t offset_row = (i1 + part_id*np1)*row_size;
  385. fin.read(reinterpret_cast<char *>(tensor->data) + offset_row, row_size);
  386. }
  387. }
  388. total_size += ggml_nbytes(tensor)/n_parts;
  389. }
  390. //fprintf(stderr, "%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ftype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
  391. if (++n_tensors % 8 == 0) {
  392. fprintf(stderr, ".");
  393. fflush(stderr);
  394. }
  395. }
  396. fprintf(stderr, " done\n");
  397. fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
  398. }
  399. fin.close();
  400. }
  401. return true;
  402. }
  403. // evaluate the transformer
  404. //
  405. // - model: the model
  406. // - n_threads: number of threads to use
  407. // - n_past: the context size so far
  408. // - embd_inp: the embeddings of the tokens in the context
  409. // - embd_w: the predicted logits for the next token
  410. //
  411. // The GPT-J model requires about 16MB of memory per input token.
  412. //
  413. bool llama_eval(
  414. const llama_model & model,
  415. const int n_threads,
  416. const int n_past,
  417. const std::vector<gpt_vocab::id> & embd_inp,
  418. std::vector<float> & embd_w,
  419. size_t & mem_per_token) {
  420. const int N = embd_inp.size();
  421. const auto & hparams = model.hparams;
  422. const int n_embd = hparams.n_embd;
  423. const int n_layer = hparams.n_layer;
  424. const int n_ctx = hparams.n_ctx;
  425. const int n_head = hparams.n_head;
  426. const int n_vocab = hparams.n_vocab;
  427. const int n_rot = hparams.n_embd/hparams.n_head;
  428. // TODO: check if this size scales with n_ctx linearly and remove constant. somehow I feel it wasn't the case
  429. // static size_t buf_size = hparams.n_ctx*1024*1024;
  430. static size_t buf_size = 512u*1024*1024;
  431. static void * buf = malloc(buf_size);
  432. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  433. const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
  434. //fprintf(stderr, "\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  435. // reallocate
  436. buf_size = buf_size_new;
  437. buf = realloc(buf, buf_size);
  438. if (buf == nullptr) {
  439. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  440. return false;
  441. }
  442. }
  443. struct ggml_init_params params = {
  444. /*.mem_size =*/ buf_size,
  445. /*.mem_buffer =*/ buf,
  446. };
  447. struct ggml_context * ctx0 = ggml_init(params);
  448. ggml_cgraph gf = {};
  449. gf.n_threads = n_threads;
  450. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  451. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  452. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  453. for (int il = 0; il < n_layer; ++il) {
  454. struct ggml_tensor * inpSA = inpL;
  455. struct ggml_tensor * cur;
  456. // norm
  457. {
  458. cur = ggml_rms_norm(ctx0, inpL);
  459. // cur = attention_norm*cur
  460. cur = ggml_mul(ctx0,
  461. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  462. cur);
  463. }
  464. // self-attention
  465. {
  466. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  467. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  468. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  469. // store key and value to memory
  470. if (N >= 1) {
  471. struct ggml_tensor * k = ggml_view_1d(ctx0, model.memory_k, N*n_embd, (ggml_element_size(model.memory_k)*n_embd)*(il*n_ctx + n_past));
  472. struct ggml_tensor * v = ggml_view_1d(ctx0, model.memory_v, N*n_embd, (ggml_element_size(model.memory_v)*n_embd)*(il*n_ctx + n_past));
  473. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  474. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  475. }
  476. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  477. struct ggml_tensor * Q =
  478. ggml_permute(ctx0,
  479. ggml_rope(ctx0,
  480. ggml_cpy(ctx0,
  481. Qcur,
  482. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  483. n_past, n_rot, 0),
  484. 0, 2, 1, 3);
  485. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  486. struct ggml_tensor * K =
  487. ggml_permute(ctx0,
  488. ggml_rope(ctx0,
  489. ggml_reshape_3d(ctx0,
  490. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  491. n_embd/n_head, n_head, n_past + N),
  492. n_past, n_rot, 1),
  493. 0, 2, 1, 3);
  494. // K * Q
  495. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  496. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  497. struct ggml_tensor * KQ_scaled =
  498. ggml_scale(ctx0,
  499. KQ,
  500. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  501. );
  502. // KQ_masked = mask_past(KQ_scaled)
  503. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  504. // KQ = soft_max(KQ_masked)
  505. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  506. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  507. struct ggml_tensor * V_trans =
  508. ggml_permute(ctx0,
  509. ggml_reshape_3d(ctx0,
  510. ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  511. n_embd/n_head, n_head, n_past + N),
  512. 1, 2, 0, 3);
  513. // KQV = transpose(V) * KQ_soft_max
  514. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  515. // KQV_merged = KQV.permute(0, 2, 1, 3)
  516. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  517. // cur = KQV_merged.contiguous().view(n_embd, N)
  518. cur = ggml_cpy(ctx0,
  519. KQV_merged,
  520. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  521. // projection (no bias)
  522. cur = ggml_mul_mat(ctx0,
  523. model.layers[il].wo,
  524. cur);
  525. }
  526. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  527. // feed-forward network
  528. {
  529. // norm
  530. {
  531. cur = ggml_rms_norm(ctx0, inpFF);
  532. // cur = ffn_norm*cur
  533. cur = ggml_mul(ctx0,
  534. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  535. cur);
  536. }
  537. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  538. model.layers[il].w3,
  539. cur);
  540. cur = ggml_mul_mat(ctx0,
  541. model.layers[il].w1,
  542. cur);
  543. // SILU activation
  544. cur = ggml_silu(ctx0, cur);
  545. cur = ggml_mul(ctx0, cur, tmp);
  546. cur = ggml_mul_mat(ctx0,
  547. model.layers[il].w2,
  548. cur);
  549. }
  550. cur = ggml_add(ctx0, cur, inpFF);
  551. // input for next layer
  552. inpL = cur;
  553. }
  554. // norm
  555. {
  556. inpL = ggml_rms_norm(ctx0, inpL);
  557. // inpL = norm*inpL
  558. inpL = ggml_mul(ctx0,
  559. ggml_repeat(ctx0, model.norm, inpL),
  560. inpL);
  561. }
  562. // lm_head
  563. {
  564. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  565. }
  566. // logits -> probs
  567. //inpL = ggml_soft_max(ctx0, inpL);
  568. // run the computation
  569. ggml_build_forward_expand(&gf, inpL);
  570. ggml_graph_compute (ctx0, &gf);
  571. //if (n_past%100 == 0) {
  572. // ggml_graph_print (&gf);
  573. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  574. //}
  575. //embd_w.resize(n_vocab*N);
  576. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  577. // return result for just the last token
  578. embd_w.resize(n_vocab);
  579. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  580. if (mem_per_token == 0) {
  581. mem_per_token = ggml_used_mem(ctx0)/N;
  582. }
  583. //fprintf(stderr, "used_mem = %zu\n", ggml_used_mem(ctx0));
  584. ggml_free(ctx0);
  585. return true;
  586. }
  587. static bool is_interacting = false;
  588. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  589. void sigint_handler(int signo) {
  590. printf(ANSI_COLOR_RESET);
  591. printf("\n"); // this also force flush stdout.
  592. if (signo == SIGINT) {
  593. if (!is_interacting) {
  594. is_interacting=true;
  595. } else {
  596. _exit(130);
  597. }
  598. }
  599. }
  600. #endif
  601. const char * llama_print_system_info(void) {
  602. static std::string s;
  603. s = "";
  604. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  605. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  606. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  607. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  608. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  609. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  610. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  611. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  612. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  613. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  614. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  615. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  616. return s.c_str();
  617. }
  618. int main(int argc, char ** argv) {
  619. ggml_time_init();
  620. const int64_t t_main_start_us = ggml_time_us();
  621. gpt_params params;
  622. params.model = "models/llama-7B/ggml-model.bin";
  623. if (gpt_params_parse(argc, argv, params) == false) {
  624. return 1;
  625. }
  626. if (params.n_ctx > 2048) {
  627. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  628. "expect poor results\n", __func__, params.n_ctx);
  629. }
  630. if (params.seed < 0) {
  631. params.seed = time(NULL);
  632. }
  633. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  634. std::mt19937 rng(params.seed);
  635. if (params.prompt.empty()) {
  636. params.prompt = gpt_random_prompt(rng);
  637. }
  638. // params.prompt = R"(// this function checks if the number n is prime
  639. //bool is_prime(int n) {)";
  640. int64_t t_load_us = 0;
  641. gpt_vocab vocab;
  642. llama_model model;
  643. // load the model
  644. {
  645. const ggml_type memory_type = params.memory_f16 ? GGML_TYPE_F16 : GGML_TYPE_F32;
  646. const int64_t t_start_us = ggml_time_us();
  647. if (!llama_model_load(params.model, model, vocab, params.n_ctx, memory_type)) {
  648. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  649. return 1;
  650. }
  651. t_load_us = ggml_time_us() - t_start_us;
  652. }
  653. // print system information
  654. {
  655. fprintf(stderr, "\n");
  656. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  657. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  658. }
  659. int n_past = 0;
  660. int64_t t_sample_us = 0;
  661. int64_t t_predict_us = 0;
  662. std::vector<float> logits;
  663. // Add a space in front of the first character to match OG llama tokenizer behavior
  664. params.prompt.insert(0, 1, ' ');
  665. // tokenize the prompt
  666. std::vector<gpt_vocab::id> embd_inp = ::llama_tokenize(vocab, params.prompt, true);
  667. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  668. // prefix & suffix for instruct mode
  669. const std::vector<gpt_vocab::id> inp_pfx = ::llama_tokenize(vocab, "\n\n### Instruction:\n\n", true);
  670. const std::vector<gpt_vocab::id> inp_sfx = ::llama_tokenize(vocab, "\n\n### Response:\n\n", false);
  671. // in instruct mode, we inject a prefix and a suffix to each input by the user
  672. if (params.instruct) {
  673. params.interactive = true;
  674. params.antiprompt = "### Instruction:\n\n";
  675. }
  676. // tokenize the reverse prompt
  677. std::vector<gpt_vocab::id> antiprompt_inp = ::llama_tokenize(vocab, params.antiprompt, false);
  678. // enable interactive mode if reverse prompt is specified
  679. if (!antiprompt_inp.empty()) {
  680. params.interactive = true;
  681. }
  682. fprintf(stderr, "\n");
  683. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  684. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  685. for (int i = 0; i < (int) embd_inp.size(); i++) {
  686. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
  687. }
  688. fprintf(stderr, "\n");
  689. if (params.interactive) {
  690. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  691. struct sigaction sigint_action;
  692. sigint_action.sa_handler = sigint_handler;
  693. sigemptyset (&sigint_action.sa_mask);
  694. sigint_action.sa_flags = 0;
  695. sigaction(SIGINT, &sigint_action, NULL);
  696. #elif defined (_WIN32)
  697. signal(SIGINT, sigint_handler);
  698. #endif
  699. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  700. if (antiprompt_inp.size()) {
  701. fprintf(stderr, "%s: reverse prompt: '%s'\n", __func__, params.antiprompt.c_str());
  702. fprintf(stderr, "%s: number of tokens in reverse prompt = %zu\n", __func__, antiprompt_inp.size());
  703. for (int i = 0; i < (int) antiprompt_inp.size(); i++) {
  704. fprintf(stderr, "%6d -> '%s'\n", antiprompt_inp[i], vocab.id_to_token.at(antiprompt_inp[i]).c_str());
  705. }
  706. fprintf(stderr, "\n");
  707. }
  708. }
  709. fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n", params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  710. fprintf(stderr, "\n\n");
  711. std::vector<gpt_vocab::id> embd;
  712. // determine the required inference memory per token:
  713. size_t mem_per_token = 0;
  714. llama_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  715. int last_n_size = params.repeat_last_n;
  716. std::vector<gpt_vocab::id> last_n_tokens(last_n_size);
  717. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  718. if (params.interactive) {
  719. fprintf(stderr, "== Running in interactive mode. ==\n"
  720. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  721. " - Press Ctrl+C to interject at any time.\n"
  722. #endif
  723. " - Press Return to return control to LLaMa.\n"
  724. " - If you want to submit another line, end your input in '\\'.\n\n");
  725. is_interacting = true;
  726. }
  727. int input_consumed = 0;
  728. bool input_noecho = false;
  729. int remaining_tokens = params.n_predict;
  730. // set the color for the prompt which will be output initially
  731. if (params.use_color) {
  732. printf(ANSI_COLOR_YELLOW);
  733. }
  734. while (remaining_tokens > 0 || params.interactive) {
  735. // predict
  736. if (embd.size() > 0) {
  737. const int64_t t_start_us = ggml_time_us();
  738. if (!llama_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  739. fprintf(stderr, "Failed to predict\n");
  740. return 1;
  741. }
  742. t_predict_us += ggml_time_us() - t_start_us;
  743. }
  744. n_past += embd.size();
  745. embd.clear();
  746. if (embd_inp.size() <= input_consumed) {
  747. // out of user input, sample next token
  748. const float top_k = params.top_k;
  749. const float top_p = params.top_p;
  750. const float temp = params.temp;
  751. const float repeat_penalty = params.repeat_penalty;
  752. const int n_vocab = model.hparams.n_vocab;
  753. gpt_vocab::id id = 0;
  754. {
  755. const int64_t t_start_sample_us = ggml_time_us();
  756. id = llama_sample_top_p_top_k(vocab, logits.data() + (logits.size() - n_vocab), last_n_tokens, repeat_penalty, top_k, top_p, temp, rng);
  757. last_n_tokens.erase(last_n_tokens.begin());
  758. last_n_tokens.push_back(id);
  759. t_sample_us += ggml_time_us() - t_start_sample_us;
  760. }
  761. // add it to the context
  762. embd.push_back(id);
  763. // echo this to console
  764. input_noecho = false;
  765. // decrement remaining sampling budget
  766. --remaining_tokens;
  767. } else {
  768. // some user input remains from prompt or interaction, forward it to processing
  769. while (embd_inp.size() > input_consumed) {
  770. embd.push_back(embd_inp[input_consumed]);
  771. last_n_tokens.erase(last_n_tokens.begin());
  772. last_n_tokens.push_back(embd_inp[input_consumed]);
  773. ++input_consumed;
  774. if ((int) embd.size() >= params.n_batch) {
  775. break;
  776. }
  777. }
  778. // reset color to default if we there is no pending user input
  779. if (!input_noecho && params.use_color && (int) embd_inp.size() == input_consumed) {
  780. printf(ANSI_COLOR_RESET);
  781. }
  782. }
  783. // display text
  784. if (!input_noecho) {
  785. for (auto id : embd) {
  786. printf("%s", vocab.id_to_token[id].c_str());
  787. }
  788. fflush(stdout);
  789. }
  790. // in interactive mode, and not currently processing queued inputs;
  791. // check if we should prompt the user for more
  792. if (params.interactive && embd_inp.size() <= input_consumed) {
  793. // check for reverse prompt
  794. if (antiprompt_inp.size() && std::equal(antiprompt_inp.rbegin(), antiprompt_inp.rend(), last_n_tokens.rbegin())) {
  795. // reverse prompt found
  796. is_interacting = true;
  797. }
  798. if (is_interacting) {
  799. if (params.instruct) {
  800. input_consumed = embd_inp.size();
  801. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  802. printf("\n> ");
  803. }
  804. // currently being interactive
  805. bool another_line = true;
  806. while (another_line) {
  807. fflush(stdout);
  808. char buf[256] = {0};
  809. int n_read;
  810. if (params.use_color) printf(ANSI_BOLD ANSI_COLOR_GREEN);
  811. if (scanf("%255[^\n]%n%*c", buf, &n_read) <= 0) {
  812. // presumable empty line, consume the newline
  813. std::ignore = scanf("%*c");
  814. n_read=0;
  815. }
  816. if (params.use_color) printf(ANSI_COLOR_RESET);
  817. if (n_read > 0 && buf[n_read-1]=='\\') {
  818. another_line = true;
  819. buf[n_read-1] = '\n';
  820. buf[n_read] = 0;
  821. } else {
  822. another_line = false;
  823. buf[n_read] = '\n';
  824. buf[n_read+1] = 0;
  825. }
  826. std::vector<gpt_vocab::id> line_inp = ::llama_tokenize(vocab, buf, false);
  827. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  828. if (params.instruct) {
  829. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  830. }
  831. remaining_tokens -= line_inp.size();
  832. input_noecho = true; // do not echo this again
  833. }
  834. is_interacting = false;
  835. }
  836. }
  837. // end of text token
  838. if (embd.back() == 2) {
  839. if (params.interactive) {
  840. is_interacting = true;
  841. } else {
  842. fprintf(stderr, " [end of text]\n");
  843. break;
  844. }
  845. }
  846. }
  847. #if defined (_WIN32)
  848. signal(SIGINT, SIG_DFL);
  849. #endif
  850. // report timing
  851. {
  852. const int64_t t_main_end_us = ggml_time_us();
  853. fprintf(stderr, "\n\n");
  854. fprintf(stderr, "%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  855. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  856. fprintf(stderr, "%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  857. fprintf(stderr, "%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
  858. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  859. }
  860. ggml_free(model.ctx);
  861. if (params.use_color) {
  862. printf(ANSI_COLOR_RESET);
  863. }
  864. return 0;
  865. }