main.cpp 38 KB

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