main.cpp 40 KB

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