main.cpp 38 KB

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