baby-llama.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. #include "ggml.h"
  2. #include <vector>
  3. #include <cassert>
  4. #include <random>
  5. #include <cstring>
  6. float frand() {
  7. return (float)rand()/(float)RAND_MAX;
  8. }
  9. struct random_normal_distribution {
  10. std::mt19937 gen;
  11. std::normal_distribution<float> nd;
  12. float min;
  13. float max;
  14. };
  15. void init_random_normal_distribution(struct random_normal_distribution * rnd, int seed, float mean, float std, float min, float max) {
  16. rnd->gen = std::mt19937(seed);
  17. rnd->nd = std::normal_distribution<float>{mean, std};
  18. rnd->min = min;
  19. rnd->max = max;
  20. }
  21. float frand_normal(struct random_normal_distribution * rnd) {
  22. const float r = rnd->nd(rnd->gen);
  23. return ((r < rnd->min) ? (rnd->min) : (r > rnd->max) ? (rnd->max) : r);
  24. }
  25. struct ggml_tensor * randomize_tensor(
  26. struct ggml_tensor * tensor,
  27. int ndims,
  28. const int64_t ne[],
  29. float fmin,
  30. float fmax) {
  31. switch (ndims) {
  32. case 1:
  33. for (int i0 = 0; i0 < ne[0]; i0++) {
  34. ((float *)tensor->data)[i0] = frand()*(fmax - fmin) + fmin;
  35. }
  36. break;
  37. case 2:
  38. for (int i1 = 0; i1 < ne[1]; i1++) {
  39. for (int i0 = 0; i0 < ne[0]; i0++) {
  40. ((float *)tensor->data)[i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  41. }
  42. }
  43. break;
  44. case 3:
  45. for (int i2 = 0; i2 < ne[2]; i2++) {
  46. for (int i1 = 0; i1 < ne[1]; i1++) {
  47. for (int i0 = 0; i0 < ne[0]; i0++) {
  48. ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  49. }
  50. }
  51. }
  52. break;
  53. case 4:
  54. for (int i3 = 0; i3 < ne[3]; i3++) {
  55. for (int i2 = 0; i2 < ne[2]; i2++) {
  56. for (int i1 = 0; i1 < ne[1]; i1++) {
  57. for (int i0 = 0; i0 < ne[0]; i0++) {
  58. ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  59. }
  60. }
  61. }
  62. }
  63. break;
  64. default:
  65. assert(false);
  66. };
  67. return tensor;
  68. }
  69. struct ggml_tensor * randomize_tensor_normal(
  70. struct ggml_tensor * tensor,
  71. int ndims,
  72. const int64_t ne[],
  73. struct random_normal_distribution * rnd) {
  74. switch (ndims) {
  75. case 1:
  76. for (int i0 = 0; i0 < ne[0]; i0++) {
  77. ((float *)tensor->data)[i0] = frand_normal(rnd);
  78. }
  79. break;
  80. case 2:
  81. for (int i1 = 0; i1 < ne[1]; i1++) {
  82. for (int i0 = 0; i0 < ne[0]; i0++) {
  83. ((float *)tensor->data)[i1*ne[0] + i0] = frand_normal(rnd);
  84. }
  85. }
  86. break;
  87. case 3:
  88. for (int i2 = 0; i2 < ne[2]; i2++) {
  89. for (int i1 = 0; i1 < ne[1]; i1++) {
  90. for (int i0 = 0; i0 < ne[0]; i0++) {
  91. ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand_normal(rnd);
  92. }
  93. }
  94. }
  95. break;
  96. case 4:
  97. for (int i3 = 0; i3 < ne[3]; i3++) {
  98. for (int i2 = 0; i2 < ne[2]; i2++) {
  99. for (int i1 = 0; i1 < ne[1]; i1++) {
  100. for (int i0 = 0; i0 < ne[0]; i0++) {
  101. ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand_normal(rnd);
  102. }
  103. }
  104. }
  105. }
  106. break;
  107. default:
  108. assert(false);
  109. };
  110. return tensor;
  111. }
  112. struct llama_hparams {
  113. uint32_t n_vocab = 32000;
  114. uint32_t n_ctx = 512; // this is provided as user input?
  115. uint32_t n_embd = 4096;
  116. uint32_t n_mult = 4;
  117. uint32_t n_head = 32;
  118. uint32_t n_layer = 32;
  119. uint32_t n_rot = 64;
  120. bool operator!=(const llama_hparams & other) const {
  121. return memcmp(this, &other, sizeof(llama_hparams));
  122. }
  123. };
  124. uint32_t get_n_ff(const struct llama_hparams* hparams) {
  125. const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
  126. return n_ff;
  127. }
  128. struct llama_hparams_lora {
  129. uint32_t n_vocab = 32000;
  130. uint32_t n_ctx = 512; // this is provided as user input?
  131. uint32_t n_embd = 4096;
  132. uint32_t n_mult = 4;
  133. uint32_t n_head = 32;
  134. uint32_t n_layer = 32;
  135. uint32_t n_rot = 64;
  136. uint32_t n_lora = 64;
  137. bool operator!=(const llama_hparams & other) const {
  138. return memcmp(this, &other, sizeof(llama_hparams));
  139. }
  140. };
  141. struct llama_layer {
  142. // normalization
  143. struct ggml_tensor * attention_norm;
  144. // attention
  145. struct ggml_tensor * wq;
  146. struct ggml_tensor * wk;
  147. struct ggml_tensor * wv;
  148. struct ggml_tensor * wo;
  149. // normalization
  150. struct ggml_tensor * ffn_norm;
  151. // ff
  152. struct ggml_tensor * w1;
  153. struct ggml_tensor * w2;
  154. struct ggml_tensor * w3;
  155. };
  156. struct llama_layer_lora {
  157. // normalization
  158. struct ggml_tensor * attention_norm;
  159. // attention
  160. struct ggml_tensor * wqa;
  161. struct ggml_tensor * wqb;
  162. struct ggml_tensor * wka;
  163. struct ggml_tensor * wkb;
  164. struct ggml_tensor * wva;
  165. struct ggml_tensor * wvb;
  166. struct ggml_tensor * woa;
  167. struct ggml_tensor * wob;
  168. // normalization
  169. struct ggml_tensor * ffn_norm;
  170. // ff
  171. struct ggml_tensor * w1;
  172. struct ggml_tensor * w2;
  173. struct ggml_tensor * w3;
  174. };
  175. struct llama_kv_cache {
  176. struct ggml_context * ctx = NULL;
  177. struct ggml_tensor * k;
  178. struct ggml_tensor * v;
  179. // llama_ctx_buffer buf;
  180. int n; // number of tokens currently in the cache
  181. };
  182. struct llama_model {
  183. struct ggml_context * ctx = NULL;
  184. llama_hparams hparams;
  185. struct ggml_tensor * tok_embeddings;
  186. struct ggml_tensor * norm;
  187. struct ggml_tensor * output;
  188. std::vector<llama_layer> layers;
  189. };
  190. struct llama_model_lora {
  191. struct ggml_context * ctx = NULL;
  192. llama_hparams_lora hparams;
  193. struct ggml_tensor * tok_embeddings;
  194. struct ggml_tensor * norm;
  195. struct ggml_tensor * outputa;
  196. struct ggml_tensor * outputb;
  197. std::vector<llama_layer_lora> layers;
  198. };
  199. void init_model(struct llama_model * model) {
  200. const auto & hparams = model->hparams;
  201. const uint32_t n_embd = hparams.n_embd;
  202. const uint32_t n_layer = hparams.n_layer;
  203. const uint32_t n_vocab = hparams.n_vocab;
  204. const uint32_t n_ff = get_n_ff(&hparams);
  205. struct ggml_context * ctx = model->ctx;
  206. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
  207. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
  208. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("output.weight", {n_embd, n_vocab});
  209. model->layers.resize(n_layer);
  210. for (uint32_t i = 0; i < n_layer; ++i) {
  211. auto & layer = model->layers[i];
  212. // std::string layers_i = "layers." + std::to_string(i);
  213. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
  214. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  215. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  216. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  217. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  218. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
  219. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  220. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  221. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  222. }
  223. }
  224. void init_model_lora(struct llama_model_lora * model) {
  225. const auto & hparams = model->hparams;
  226. const uint32_t n_embd = hparams.n_embd;
  227. const uint32_t n_mult = hparams.n_mult;
  228. const uint32_t n_layer = hparams.n_layer;
  229. const uint32_t n_vocab = hparams.n_vocab;
  230. const uint32_t n_lora = hparams.n_lora;
  231. const uint32_t n_ff = ((2*(4*n_embd)/3 + n_mult - 1)/n_mult)*n_mult;
  232. struct ggml_context * ctx = model->ctx;
  233. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
  234. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
  235. model->outputa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_vocab); // ("output.weight", {n_embd, n_vocab});
  236. model->outputb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // ("output.weight", {n_embd, n_vocab});
  237. model->layers.resize(n_layer);
  238. for (uint32_t i = 0; i < n_layer; ++i) {
  239. auto & layer = model->layers[i];
  240. // std::string layers_i = "layers." + std::to_string(i);
  241. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
  242. layer.wqa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  243. layer.wqb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  244. layer.wka = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  245. layer.wkb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  246. layer.wva = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  247. layer.wvb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  248. layer.woa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  249. layer.wob = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  250. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
  251. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  252. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  253. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  254. }
  255. }
  256. void set_param_model(struct llama_model * model) {
  257. const auto& hparams = model->hparams;
  258. const uint32_t n_layer = hparams.n_layer;
  259. struct ggml_context* ctx = model->ctx;
  260. ggml_set_param(ctx, model->tok_embeddings);
  261. ggml_set_param(ctx, model->norm);
  262. ggml_set_param(ctx, model->output);
  263. for (uint32_t i = 0; i < n_layer; ++i) {
  264. auto & layer = model->layers[i];
  265. ggml_set_param(ctx, layer.attention_norm);
  266. ggml_set_param(ctx, layer.wq);
  267. ggml_set_param(ctx, layer.wk);
  268. ggml_set_param(ctx, layer.wv);
  269. ggml_set_param(ctx, layer.wo);
  270. ggml_set_param(ctx, layer.ffn_norm);
  271. ggml_set_param(ctx, layer.w1);
  272. ggml_set_param(ctx, layer.w2);
  273. ggml_set_param(ctx, layer.w3);
  274. }
  275. }
  276. void set_param_model_lora(struct llama_model_lora * model) {
  277. const auto& hparams = model->hparams;
  278. const uint32_t n_layer = hparams.n_layer;
  279. struct ggml_context* ctx = model->ctx;
  280. ggml_set_param(ctx, model->tok_embeddings);
  281. ggml_set_param(ctx, model->norm);
  282. ggml_set_param(ctx, model->outputa);
  283. ggml_set_param(ctx, model->outputb);
  284. for (uint32_t i = 0; i < n_layer; ++i) {
  285. auto & layer = model->layers[i];
  286. ggml_set_param(ctx, layer.attention_norm);
  287. ggml_set_param(ctx, layer.wqa);
  288. ggml_set_param(ctx, layer.wqb);
  289. ggml_set_param(ctx, layer.wka);
  290. ggml_set_param(ctx, layer.wkb);
  291. ggml_set_param(ctx, layer.wva);
  292. ggml_set_param(ctx, layer.wvb);
  293. ggml_set_param(ctx, layer.woa);
  294. ggml_set_param(ctx, layer.wob);
  295. ggml_set_param(ctx, layer.ffn_norm);
  296. ggml_set_param(ctx, layer.w1);
  297. ggml_set_param(ctx, layer.w2);
  298. ggml_set_param(ctx, layer.w3);
  299. }
  300. }
  301. void randomize_model(struct llama_model * model, int seed, float mean, float std, float min, float max) {
  302. const auto & hparams = model->hparams;
  303. const uint32_t n_layer = hparams.n_layer;
  304. struct random_normal_distribution rnd;
  305. init_random_normal_distribution(&rnd, seed, mean, std, min, max);
  306. randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
  307. randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
  308. randomize_tensor_normal(model->output, model->output->n_dims, model->output->ne, &rnd);
  309. for (uint32_t i = 0; i < n_layer; ++i) {
  310. auto & layer = model->layers[i];
  311. randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
  312. randomize_tensor_normal(layer.wq, layer.wq->n_dims, layer.wq->ne, &rnd);
  313. randomize_tensor_normal(layer.wk, layer.wk->n_dims, layer.wk->ne, &rnd);
  314. randomize_tensor_normal(layer.wv, layer.wv->n_dims, layer.wv->ne, &rnd);
  315. randomize_tensor_normal(layer.wo, layer.wo->n_dims, layer.wo->ne, &rnd);
  316. randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
  317. randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
  318. randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
  319. randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
  320. }
  321. }
  322. void randomize_model_lora(struct llama_model_lora * model, int seed, float mean, float std, float min, float max) {
  323. const auto & hparams = model->hparams;
  324. const uint32_t n_layer = hparams.n_layer;
  325. struct random_normal_distribution rnd;
  326. init_random_normal_distribution(&rnd, seed, mean, std, min, max);
  327. randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
  328. randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
  329. randomize_tensor_normal(model->outputa, model->outputa->n_dims, model->outputa->ne, &rnd);
  330. randomize_tensor_normal(model->outputb, model->outputb->n_dims, model->outputb->ne, &rnd);
  331. for (uint32_t i = 0; i < n_layer; ++i) {
  332. auto & layer = model->layers[i];
  333. randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
  334. randomize_tensor_normal(layer.wqa, layer.wqa->n_dims, layer.wqa->ne, &rnd);
  335. randomize_tensor_normal(layer.wqb, layer.wqb->n_dims, layer.wqb->ne, &rnd);
  336. randomize_tensor_normal(layer.wka, layer.wka->n_dims, layer.wka->ne, &rnd);
  337. randomize_tensor_normal(layer.wkb, layer.wkb->n_dims, layer.wkb->ne, &rnd);
  338. randomize_tensor_normal(layer.wva, layer.wva->n_dims, layer.wva->ne, &rnd);
  339. randomize_tensor_normal(layer.wvb, layer.wvb->n_dims, layer.wvb->ne, &rnd);
  340. randomize_tensor_normal(layer.woa, layer.woa->n_dims, layer.woa->ne, &rnd);
  341. randomize_tensor_normal(layer.wob, layer.wob->n_dims, layer.wob->ne, &rnd);
  342. randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
  343. randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
  344. randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
  345. randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
  346. }
  347. }
  348. bool init_kv_cache(struct llama_kv_cache* cache, struct llama_model * model, int n_batch) {
  349. const auto & hparams = model->hparams;
  350. const uint32_t n_ctx = hparams.n_ctx;
  351. const uint32_t n_embd = hparams.n_embd;
  352. const uint32_t n_layer = hparams.n_layer;
  353. const int64_t n_mem = n_layer*n_ctx*n_batch;
  354. const int64_t n_elements = n_embd*n_mem;
  355. // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  356. // struct ggml_init_params params;
  357. // params.mem_size = cache.buf.size;
  358. // params.mem_buffer = cache.buf.addr;
  359. // params.no_alloc = false;
  360. if (!cache->ctx) {
  361. struct ggml_init_params params;
  362. params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
  363. params.mem_buffer = NULL;
  364. params.no_alloc = false;
  365. cache->ctx = ggml_init(params);
  366. if (!cache->ctx) {
  367. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  368. return false;
  369. }
  370. }
  371. cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  372. cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  373. return true;
  374. }
  375. bool init_kv_cache_lora(struct llama_kv_cache* cache, struct llama_model_lora * model, int n_batch) {
  376. const auto & hparams = model->hparams;
  377. const uint32_t n_ctx = hparams.n_ctx;
  378. const uint32_t n_embd = hparams.n_embd;
  379. const uint32_t n_layer = hparams.n_layer;
  380. const int64_t n_mem = n_layer*n_ctx*n_batch;
  381. const int64_t n_elements = n_embd*n_mem;
  382. // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  383. // struct ggml_init_params params;
  384. // params.mem_size = cache.buf.size;
  385. // params.mem_buffer = cache.buf.addr;
  386. // params.no_alloc = false;
  387. if (!cache->ctx) {
  388. struct ggml_init_params params;
  389. params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
  390. params.mem_buffer = NULL;
  391. params.no_alloc = false;
  392. cache->ctx = ggml_init(params);
  393. if (!cache->ctx) {
  394. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  395. return false;
  396. }
  397. }
  398. cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  399. cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  400. return true;
  401. }
  402. struct ggml_tensor * forward(
  403. struct llama_model * model,
  404. struct llama_kv_cache * cache,
  405. struct ggml_context * ctx0,
  406. struct ggml_cgraph * gf,
  407. struct ggml_tensor * tokens_input,
  408. const int n_tokens,
  409. const int n_past) {
  410. const int N = n_tokens;
  411. struct llama_kv_cache& kv_self = *cache;
  412. const auto & hparams = model->hparams;
  413. const int n_ctx = hparams.n_ctx;
  414. const int n_embd = hparams.n_embd;
  415. const int n_layer = hparams.n_layer;
  416. const int n_head = hparams.n_head;
  417. const int n_rot = hparams.n_rot;
  418. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  419. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  420. struct ggml_tensor * kc = kv_self.k;
  421. struct ggml_tensor * vc = kv_self.v;
  422. // inpL shape [n_embd,N,1,1]
  423. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  424. for (int il = 0; il < n_layer; ++il) {
  425. struct ggml_tensor * inpSA = inpL;
  426. struct ggml_tensor * cur;
  427. // lctx.use_buf(ctx0, 0);
  428. // norm
  429. {
  430. // cur shape [n_embd,N,1,1]
  431. cur = ggml_rms_norm(ctx0, inpL);
  432. // cur = attention_norm*cur
  433. cur = ggml_mul(ctx0,
  434. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  435. cur);
  436. }
  437. // self-attention
  438. {
  439. // compute Q and K and RoPE them
  440. // wq shape [n_embd, n_embd, 1, 1]
  441. // wk shape [n_embd, n_embd, 1, 1]
  442. // Qcur shape [n_embd/n_head, n_head, N, 1]
  443. // Kcur shape [n_embd/n_head, n_head, N, 1]
  444. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  445. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  446. // store key and value to memory
  447. {
  448. // compute the transposed [N, n_embd] V matrix
  449. // wv shape [n_embd, n_embd, 1, 1]
  450. // Vcur shape [n_embd, N, 1, 1]
  451. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wv, cur), n_embd, N)));
  452. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  453. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  454. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  455. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  456. /* {
  457. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  458. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  459. ( n_ctx)*ggml_element_size(kv_self.v),
  460. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  461. // important: storing RoPE-ed version of K in the KV cache!
  462. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  463. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  464. } //*/
  465. kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  466. vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  467. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  468. }
  469. // Qcur shape [n_embd/n_head, n_head, N, 1]
  470. // Q shape [n_embd/n_head, N, n_head, 1]
  471. struct ggml_tensor * Q =
  472. ggml_permute(ctx0,
  473. Qcur,
  474. 0, 2, 1, 3);
  475. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  476. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  477. struct ggml_tensor * K =
  478. ggml_permute(ctx0,
  479. ggml_reshape_3d(ctx0,
  480. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  481. n_embd/n_head, n_head, n_past + N),
  482. 0, 2, 1, 3);
  483. // K * Q
  484. // KQ shape [n_past + N, N, n_head, 1]
  485. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  486. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  487. // KQ_scaled shape [n_past + N, N, n_head, 1]
  488. struct ggml_tensor * KQ_scaled =
  489. ggml_scale(ctx0,
  490. KQ,
  491. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  492. // KQ_masked = mask_past(KQ_scaled)
  493. // KQ_masked shape [n_past + N, N, n_head, 1]
  494. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  495. // KQ = soft_max(KQ_masked)
  496. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  497. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  498. // split cached V into n_head heads
  499. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  500. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  501. struct ggml_tensor * V =
  502. ggml_view_3d(ctx0, vc,
  503. n_past + N, n_embd/n_head, n_head,
  504. n_ctx*ggml_element_size(vc),
  505. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  506. il*n_ctx*ggml_element_size(vc)*n_embd);
  507. // KQV shape [n_embd/n_head, N, n_head, 1]
  508. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  509. // KQV_merged = KQV.permute(0, 2, 1, 3)
  510. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  511. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  512. // KQV_merged shape
  513. // cur = KQV_merged.contiguous().view(n_embd, N)
  514. // cur shape [n_embd,N,1,1]
  515. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  516. // cur = ggml_cpy(ctx0,
  517. // KQV_merged,
  518. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  519. // projection (no bias)
  520. // cur shape [n_embd,N,1,1]
  521. cur = ggml_mul_mat(ctx0,
  522. model->layers[il].wo,
  523. cur);
  524. }
  525. // lctx.use_buf(ctx0, 1);
  526. // inpFF shape [n_embd,N,1,1]
  527. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  528. // feed-forward network
  529. {
  530. // norm
  531. {
  532. // cur shape [n_embd,N,1,1]
  533. cur = ggml_rms_norm(ctx0, inpFF);
  534. // cur = ffn_norm*cur
  535. // cur shape [n_embd,N,1,1]
  536. cur = ggml_mul(ctx0,
  537. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  538. cur);
  539. }
  540. // tmp shape [n_ff,N,1,1]
  541. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  542. model->layers[il].w3,
  543. cur);
  544. // cur shape [n_ff,N,1,1]
  545. cur = ggml_mul_mat(ctx0,
  546. model->layers[il].w1,
  547. cur);
  548. // SILU activation
  549. // cur shape [n_ff,N,1,1]
  550. cur = ggml_silu(ctx0, cur);
  551. // cur shape [n_ff,N,1,1]
  552. cur = ggml_mul(ctx0, cur, tmp);
  553. // cur shape [n_embd,N,1,1]
  554. cur = ggml_mul_mat(ctx0,
  555. model->layers[il].w2,
  556. cur);
  557. }
  558. // cur shape [n_embd,N,1,1]
  559. cur = ggml_add(ctx0, cur, inpFF);
  560. // input for next layer
  561. // inpL shape [n_embd,N,1,1]
  562. inpL = cur;
  563. }
  564. // norm
  565. {
  566. // inpL shape [n_embd,N,1,1]
  567. inpL = ggml_rms_norm(ctx0, inpL);
  568. // inpL = norm*inpL
  569. // inpL shape [n_embd,N,1,1]
  570. inpL = ggml_mul(ctx0,
  571. ggml_repeat(ctx0, model->norm, inpL),
  572. inpL);
  573. //embeddings = inpL;
  574. }
  575. // lm_head
  576. // inpL shape [n_vocab,N,1,1]
  577. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  578. // run the computation
  579. ggml_build_forward_expand(gf, inpL);
  580. return inpL;
  581. }
  582. void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
  583. GGML_ASSERT(tensor->n_dims == 1);
  584. GGML_ASSERT(tensor->ne[0] == ne0);
  585. }
  586. void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
  587. GGML_ASSERT(tensor->n_dims == 2);
  588. GGML_ASSERT(tensor->ne[0] == ne0);
  589. GGML_ASSERT(tensor->ne[1] == ne1);
  590. }
  591. void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
  592. GGML_ASSERT(tensor->n_dims == 3);
  593. GGML_ASSERT(tensor->ne[0] == ne0);
  594. GGML_ASSERT(tensor->ne[1] == ne1);
  595. GGML_ASSERT(tensor->ne[2] == ne2);
  596. }
  597. void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  598. GGML_ASSERT(tensor->n_dims == 4);
  599. GGML_ASSERT(tensor->ne[0] == ne0);
  600. GGML_ASSERT(tensor->ne[1] == ne1);
  601. GGML_ASSERT(tensor->ne[2] == ne2);
  602. GGML_ASSERT(tensor->ne[3] == ne3);
  603. }
  604. struct ggml_tensor * forward_batch(
  605. struct llama_model * model,
  606. struct llama_kv_cache * cache,
  607. struct ggml_context * ctx0,
  608. struct ggml_cgraph * gf,
  609. struct ggml_tensor * tokens_input,
  610. const int n_tokens,
  611. const int n_past,
  612. const int n_batch) {
  613. const int N = n_tokens;
  614. struct llama_kv_cache& kv_self = *cache;
  615. const auto & hparams = model->hparams;
  616. const int n_ctx = hparams.n_ctx;
  617. const int n_vocab = hparams.n_vocab;
  618. const int n_embd = hparams.n_embd;
  619. const int n_layer = hparams.n_layer;
  620. const int n_head = hparams.n_head;
  621. const int n_rot = hparams.n_rot;
  622. const int n_ff = get_n_ff(&hparams);
  623. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  624. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  625. struct ggml_tensor * kc = kv_self.k;
  626. struct ggml_tensor * vc = kv_self.v;
  627. // inpL shape [n_embd,N*n_batch,1]
  628. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  629. assert_shape_2d(inpL, n_embd, N*n_batch);
  630. for (int il = 0; il < n_layer; ++il) {
  631. struct ggml_tensor * inpSA = inpL;
  632. struct ggml_tensor * cur;
  633. // lctx.use_buf(ctx0, 0);
  634. // norm
  635. {
  636. // cur shape [n_embd,N*n_batch,1,1]
  637. cur = ggml_rms_norm(ctx0, inpL);
  638. assert_shape_2d(cur, n_embd, N*n_batch);
  639. // cur = attention_norm*cur
  640. cur = ggml_mul(ctx0,
  641. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  642. cur);
  643. assert_shape_2d(cur, n_embd, N*n_batch);
  644. }
  645. // self-attention
  646. {
  647. // compute Q and K and RoPE them
  648. // wq shape [n_embd, n_embd, 1, 1]
  649. // wk shape [n_embd, n_embd, 1, 1]
  650. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  651. // Kcur shape [n_embd/n_head, n_head, N, n_batch]
  652. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N, n_batch), n_past, n_rot, 0);
  653. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N, n_batch), n_past, n_rot, 0);
  654. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  655. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  656. // store key and value to memory
  657. {
  658. // compute the transposed [N, n_embd] V matrix
  659. // wv shape [n_embd, n_embd, 1, 1]
  660. // Vcur shape [N, n_embd, n_batch, 1]
  661. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  662. ggml_permute(ctx0,
  663. ggml_reshape_3d(ctx0,
  664. ggml_mul_mat(ctx0,
  665. model->layers[il].wv,
  666. cur),
  667. n_embd, N, n_batch),
  668. 1, 0, 2, 3));
  669. assert_shape_3d(Vcur, N, n_embd, n_batch);
  670. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  671. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  672. // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
  673. // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
  674. /* {
  675. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  676. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  677. ( n_ctx)*ggml_element_size(kv_self.v),
  678. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  679. // important: storing RoPE-ed version of K in the KV cache!
  680. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  681. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  682. } //*/
  683. kc = ggml_set_2d(ctx0, kc,
  684. ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
  685. ggml_element_size(kc)*n_embd*n_ctx,
  686. (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
  687. vc = ggml_set_2d(ctx0, vc,
  688. ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
  689. ggml_element_size(vc)*n_ctx*n_embd,
  690. ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
  691. assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
  692. assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
  693. }
  694. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  695. // Q shape [n_embd/n_head, N, n_head, n_batch]
  696. struct ggml_tensor * Q =
  697. ggml_permute(ctx0,
  698. Qcur,
  699. 0, 2, 1, 3);
  700. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  701. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  702. // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
  703. struct ggml_tensor * K =
  704. ggml_permute(ctx0,
  705. ggml_reshape_4d(ctx0,
  706. ggml_view_3d(ctx0,
  707. kc,
  708. n_embd,
  709. (n_past + N),
  710. n_batch,
  711. n_embd*ggml_element_size(kc),
  712. n_ctx*n_embd*ggml_element_size(kc),
  713. il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
  714. n_embd/n_head, n_head, n_past + N, n_batch),
  715. 0, 2, 1, 3);
  716. assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
  717. // K * Q
  718. // KQ shape [n_past + N, N, n_head, n_batch]
  719. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  720. assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
  721. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  722. // KQ_scaled shape [n_past + N, N, n_head, n_batch]
  723. struct ggml_tensor * KQ_scaled =
  724. ggml_scale(ctx0,
  725. KQ,
  726. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  727. assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
  728. // KQ_masked = mask_past(KQ_scaled)
  729. // KQ_masked shape [n_past + N, N, n_head, n_batch]
  730. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  731. assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
  732. // KQ = soft_max(KQ_masked)
  733. // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
  734. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  735. assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
  736. // split cached V into n_head heads
  737. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  738. // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
  739. struct ggml_tensor * V =
  740. ggml_view_4d(ctx0, vc,
  741. n_past + N, n_embd/n_head, n_head, n_batch,
  742. ggml_element_size(vc)*n_ctx,
  743. ggml_element_size(vc)*n_ctx*n_embd/n_head,
  744. ggml_element_size(vc)*n_ctx*n_embd,
  745. il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
  746. assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
  747. // KQV shape [n_embd/n_head, N, n_head, n_batch]
  748. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  749. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  750. // KQV_merged = KQV.permute(0, 2, 1, 3)
  751. // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
  752. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  753. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  754. // KQV_merged shape
  755. // cur = KQV_merged.contiguous().view(n_embd, N)
  756. // cur shape [n_embd,N*n_batch,1,1]
  757. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  758. assert_shape_2d(cur, n_embd, N*n_batch);
  759. // cur = ggml_cpy(ctx0,
  760. // KQV_merged,
  761. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  762. // projection (no bias)
  763. // cur shape [n_embd,N*n_batch,1,1]
  764. cur = ggml_mul_mat(ctx0,
  765. model->layers[il].wo,
  766. cur);
  767. assert_shape_2d(cur, n_embd, N*n_batch);
  768. }
  769. // lctx.use_buf(ctx0, 1);
  770. // inpFF shape [n_embd,N*n_batch,1,1]
  771. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  772. assert_shape_2d(inpFF, n_embd, N*n_batch);
  773. // feed-forward network
  774. {
  775. // norm
  776. {
  777. // cur shape [n_embd,N*n_batch,1,1]
  778. cur = ggml_rms_norm(ctx0, inpFF);
  779. assert_shape_2d(cur, n_embd, N*n_batch);
  780. // cur = ffn_norm*cur
  781. // cur shape [n_embd,N*n_batch,1,1]
  782. cur = ggml_mul(ctx0,
  783. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  784. cur);
  785. assert_shape_2d(cur, n_embd, N*n_batch);
  786. }
  787. // tmp shape [n_ff,N*n_batch,1,1]
  788. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  789. model->layers[il].w3,
  790. cur);
  791. assert_shape_2d(tmp, n_ff, N*n_batch);
  792. // cur shape [n_ff,N*n_batch,1,1]
  793. cur = ggml_mul_mat(ctx0,
  794. model->layers[il].w1,
  795. cur);
  796. assert_shape_2d(cur, n_ff, N*n_batch);
  797. // SILU activation
  798. // cur shape [n_ff,N*n_batch,1,1]
  799. cur = ggml_silu(ctx0, cur);
  800. assert_shape_2d(cur, n_ff, N*n_batch);
  801. // cur shape [n_ff,N*n_batch,1,1]
  802. cur = ggml_mul(ctx0, cur, tmp);
  803. assert_shape_2d(cur, n_ff, N*n_batch);
  804. // cur shape [n_embd,N*n_batch,1,1]
  805. cur = ggml_mul_mat(ctx0,
  806. model->layers[il].w2,
  807. cur);
  808. assert_shape_2d(cur, n_embd, N*n_batch);
  809. }
  810. // cur shape [n_embd,N*n_batch,1,1]
  811. cur = ggml_add(ctx0, cur, inpFF);
  812. assert_shape_2d(cur, n_embd, N*n_batch);
  813. // input for next layer
  814. // inpL shape [n_embd,N*n_batch,1,1]
  815. inpL = cur;
  816. assert_shape_2d(inpL, n_embd, N*n_batch);
  817. }
  818. // norm
  819. {
  820. // inpL shape [n_embd,N*n_batch,1,1]
  821. inpL = ggml_rms_norm(ctx0, inpL);
  822. assert_shape_2d(inpL, n_embd, N*n_batch);
  823. // inpL = norm*inpL
  824. // inpL shape [n_embd,N*n_batch,1,1]
  825. inpL = ggml_mul(ctx0,
  826. ggml_repeat(ctx0, model->norm, inpL),
  827. inpL);
  828. assert_shape_2d(inpL, n_embd, N*n_batch);
  829. //embeddings = inpL;
  830. }
  831. // lm_head
  832. // inpL shape [n_vocab,N*n_batch,1,1]
  833. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  834. assert_shape_2d(inpL, n_vocab, N*n_batch);
  835. {
  836. // inpL shape [n_vocab,N,n_batch,1]
  837. inpL = ggml_reshape_3d(ctx0,
  838. inpL,
  839. n_vocab, N, n_batch);
  840. assert_shape_3d(inpL, n_vocab, N, n_batch);
  841. }
  842. // run the computation
  843. ggml_build_forward_expand(gf, inpL);
  844. return inpL;
  845. }
  846. struct ggml_tensor * forward_lora(
  847. struct llama_model_lora * model,
  848. struct llama_kv_cache * cache,
  849. struct ggml_context * ctx0,
  850. struct ggml_cgraph * gf,
  851. struct ggml_tensor * tokens_input,
  852. const int n_tokens,
  853. const int n_past) {
  854. const int N = n_tokens;
  855. struct llama_kv_cache& kv_self = *cache;
  856. const auto & hparams = model->hparams;
  857. const int n_ctx = hparams.n_ctx;
  858. const int n_embd = hparams.n_embd;
  859. const int n_layer = hparams.n_layer;
  860. const int n_head = hparams.n_head;
  861. const int n_rot = hparams.n_rot;
  862. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  863. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  864. struct ggml_tensor * kc = kv_self.k;
  865. struct ggml_tensor * vc = kv_self.v;
  866. // inpL shape [n_embd,N,1,1]
  867. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  868. for (int il = 0; il < n_layer; ++il) {
  869. struct ggml_tensor * inpSA = inpL;
  870. struct ggml_tensor * cur;
  871. // norm
  872. {
  873. // cur shape [n_embd,N,1,1]
  874. cur = ggml_rms_norm(ctx0, inpL);
  875. // cur = attention_norm*cur
  876. cur = ggml_mul(ctx0,
  877. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  878. cur);
  879. }
  880. // self-attention
  881. {
  882. // compute Q and K and RoPE them
  883. // wq shape [n_embd, n_embd, 1, 1]
  884. // wk shape [n_embd, n_embd, 1, 1]
  885. // Qcur shape [n_embd/n_head, n_head, N, 1]
  886. // Kcur shape [n_embd/n_head, n_head, N, 1]
  887. struct ggml_tensor * Qcur = ggml_rope(ctx0,
  888. ggml_reshape_3d(ctx0,
  889. ggml_mul_mat(ctx0,
  890. model->layers[il].wqa,
  891. ggml_mul_mat(ctx0,
  892. model->layers[il].wqb,
  893. cur)),
  894. n_embd/n_head, n_head, N),
  895. n_past, n_rot, 0);
  896. struct ggml_tensor * Kcur = ggml_rope(ctx0,
  897. ggml_reshape_3d(ctx0,
  898. ggml_mul_mat(ctx0,
  899. model->layers[il].wka,
  900. ggml_mul_mat(ctx0,
  901. model->layers[il].wkb,
  902. cur)),
  903. n_embd/n_head, n_head, N),
  904. n_past, n_rot, 0);
  905. // store key and value to memory
  906. {
  907. // compute the transposed [N, n_embd] V matrix
  908. // wv shape [n_embd, n_embd, 1, 1]
  909. // Vcur shape [n_embd, N, 1, 1]
  910. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  911. ggml_transpose(ctx0,
  912. ggml_reshape_2d(ctx0,
  913. ggml_mul_mat(ctx0,
  914. model->layers[il].wva,
  915. ggml_mul_mat(ctx0,
  916. model->layers[il].wvb,
  917. cur)),
  918. n_embd, N)));
  919. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  920. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  921. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  922. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  923. /* {
  924. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  925. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  926. ( n_ctx)*ggml_element_size(kv_self.v),
  927. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  928. // important: storing RoPE-ed version of K in the KV cache!
  929. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  930. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  931. } //*/
  932. kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  933. vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  934. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  935. }
  936. // Qcur shape [n_embd/n_head, n_head, N, 1]
  937. // Q shape [n_embd/n_head, N, n_head, 1]
  938. struct ggml_tensor * Q =
  939. ggml_permute(ctx0,
  940. Qcur,
  941. 0, 2, 1, 3);
  942. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  943. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  944. struct ggml_tensor * K =
  945. ggml_permute(ctx0,
  946. ggml_reshape_3d(ctx0,
  947. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  948. n_embd/n_head, n_head, n_past + N),
  949. 0, 2, 1, 3);
  950. // K * Q
  951. // KQ shape [n_past + N, N, n_head, 1]
  952. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  953. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  954. // KQ_scaled shape [n_past + N, N, n_head, 1]
  955. struct ggml_tensor * KQ_scaled =
  956. ggml_scale(ctx0,
  957. KQ,
  958. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  959. // KQ_masked = mask_past(KQ_scaled)
  960. // KQ_masked shape [n_past + N, N, n_head, 1]
  961. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  962. // KQ = soft_max(KQ_masked)
  963. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  964. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  965. // split cached V into n_head heads
  966. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  967. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  968. struct ggml_tensor * V =
  969. ggml_view_3d(ctx0, vc,
  970. n_past + N, n_embd/n_head, n_head,
  971. n_ctx*ggml_element_size(vc),
  972. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  973. il*n_ctx*ggml_element_size(vc)*n_embd);
  974. // KQV shape [n_embd/n_head, N, n_head, 1]
  975. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  976. // KQV_merged = KQV.permute(0, 2, 1, 3)
  977. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  978. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  979. // KQV_merged shape
  980. // cur = KQV_merged.contiguous().view(n_embd, N)
  981. // cur shape [n_embd,N,1,1]
  982. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  983. // cur = ggml_cpy(ctx0,
  984. // KQV_merged,
  985. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  986. // projection (no bias)
  987. // cur shape [n_embd,N,1,1]
  988. cur = ggml_mul_mat(ctx0,
  989. model->layers[il].woa,
  990. ggml_mul_mat(ctx0,
  991. model->layers[il].wob,
  992. cur));
  993. }
  994. // inpFF shape [n_embd,N,1,1]
  995. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  996. // feed-forward network
  997. {
  998. // norm
  999. {
  1000. // cur shape [n_embd,N,1,1]
  1001. cur = ggml_rms_norm(ctx0, inpFF);
  1002. // cur = ffn_norm*cur
  1003. // cur shape [n_embd,N,1,1]
  1004. cur = ggml_mul(ctx0,
  1005. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  1006. cur);
  1007. }
  1008. // tmp shape [n_ff,N,1,1]
  1009. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1010. model->layers[il].w3,
  1011. cur);
  1012. // cur shape [n_ff,N,1,1]
  1013. cur = ggml_mul_mat(ctx0,
  1014. model->layers[il].w1,
  1015. cur);
  1016. // SILU activation
  1017. // cur shape [n_ff,N,1,1]
  1018. cur = ggml_silu(ctx0, cur);
  1019. // cur shape [n_ff,N,1,1]
  1020. cur = ggml_mul(ctx0, cur, tmp);
  1021. // cur shape [n_embd,N,1,1]
  1022. cur = ggml_mul_mat(ctx0,
  1023. model->layers[il].w2,
  1024. cur);
  1025. }
  1026. // cur shape [n_embd,N,1,1]
  1027. cur = ggml_add(ctx0, cur, inpFF);
  1028. // input for next layer
  1029. // inpL shape [n_embd,N,1,1]
  1030. inpL = cur;
  1031. }
  1032. // norm
  1033. {
  1034. // inpL shape [n_embd,N,1,1]
  1035. inpL = ggml_rms_norm(ctx0, inpL);
  1036. // inpL = norm*inpL
  1037. // inpL shape [n_embd,N,1,1]
  1038. inpL = ggml_mul(ctx0,
  1039. ggml_repeat(ctx0, model->norm, inpL),
  1040. inpL);
  1041. //embeddings = inpL;
  1042. }
  1043. // lm_head
  1044. // inpL shape [n_vocab,N,1,1]
  1045. inpL = ggml_mul_mat(ctx0,
  1046. model->outputa,
  1047. ggml_mul_mat(ctx0,
  1048. model->outputb,
  1049. inpL));
  1050. // ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  1051. // run the computation
  1052. ggml_build_forward_expand(gf, inpL);
  1053. return inpL;
  1054. }
  1055. void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
  1056. assert(logits->n_dims == 2);
  1057. assert(probs->n_dims == 2);
  1058. assert(best_samples->n_dims == 1);
  1059. assert(logits->ne[1] == best_samples->ne[0]);
  1060. assert(logits->ne[0] == probs->ne[0]);
  1061. assert(logits->ne[1] == probs->ne[1]);
  1062. for (int i = 0; i < logits->ne[1]; ++i) {
  1063. float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
  1064. ggml_set_i32_1d(best_samples, i, 0);
  1065. for (int k = 0; k < logits->ne[0]; ++k) {
  1066. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1067. if (logit > max_logit) {
  1068. max_logit = logit;
  1069. ggml_set_i32_1d(best_samples, i, k);
  1070. }
  1071. }
  1072. float psum = 0;
  1073. for (int k = 0; k < logits->ne[0]; ++k) {
  1074. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1075. float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
  1076. psum += p;
  1077. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
  1078. }
  1079. for (int k = 0; k < logits->ne[0]; ++k) {
  1080. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1081. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
  1082. }
  1083. }
  1084. }
  1085. void sample_softmax_batch(struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
  1086. GGML_ASSERT(best_samples->n_dims == 2);
  1087. GGML_ASSERT(logits->n_dims == 3);
  1088. GGML_ASSERT(probs->n_dims == 3);
  1089. int n_tokens = best_samples->ne[0];
  1090. int n_batch = best_samples->ne[1];
  1091. int n_vocab = logits->ne[0];
  1092. GGML_ASSERT(n_tokens == logits->ne[1]);
  1093. GGML_ASSERT(n_batch == logits->ne[2]);
  1094. GGML_ASSERT(n_vocab == probs->ne[0]);
  1095. GGML_ASSERT(n_tokens == probs->ne[1]);
  1096. GGML_ASSERT(n_batch == probs->ne[2]);
  1097. for (int k = 0; k < n_batch; ++k) {
  1098. struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
  1099. best_samples,
  1100. best_samples->ne[0],
  1101. k*best_samples->nb[1]);
  1102. struct ggml_tensor * logits_k = ggml_view_2d(ctx,
  1103. logits,
  1104. logits->ne[0],
  1105. logits->ne[1],
  1106. logits->nb[1],
  1107. k*logits->nb[2]);
  1108. struct ggml_tensor * probs_k = ggml_view_2d(ctx,
  1109. probs,
  1110. probs->ne[0],
  1111. probs->ne[1],
  1112. probs->nb[1],
  1113. k*probs->nb[2]);
  1114. sample_softmax(logits_k, probs_k, best_samples_k);
  1115. }
  1116. }
  1117. void print_row(struct ggml_tensor * probs, int i) {
  1118. for (int k = 0; k < probs->ne[0]; ++k) {
  1119. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1120. printf(" %.2f", p);
  1121. }
  1122. printf("\n");
  1123. }
  1124. void print_matrix(struct ggml_tensor * probs) {
  1125. assert(probs->n_dims == 2);
  1126. for (int i = 0; i < probs->ne[1]; ++i) {
  1127. for (int k = 0; k < probs->ne[0]; ++k) {
  1128. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1129. printf(" %.2f", p);
  1130. }
  1131. printf("\n");
  1132. }
  1133. }
  1134. void print_token(int token, int n_vocab) {
  1135. for (int k = 0; k < token; ++k) {
  1136. printf(" ");
  1137. }
  1138. printf("X");
  1139. for (int k = token+1; k < n_vocab; ++k) {
  1140. printf(" ");
  1141. }
  1142. printf("\n");
  1143. }
  1144. void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
  1145. for (int i=0; i<tokens->ne[0]; ++i) {
  1146. int token = ggml_get_i32_1d(tokens, i);
  1147. print_token(token, n_vocab);
  1148. }
  1149. }
  1150. void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
  1151. int n_tokens = tokens_input->ne[0];
  1152. int n_vocab = targets->ne[0];
  1153. float randomness = 0.0f;
  1154. // ggml_set_zero(targets);
  1155. ggml_set_f32(targets, -1.0f);
  1156. ggml_set_i32_1d(tokens_input, 0, 0);
  1157. for (int i=1; i<n_tokens+1; ++i) {
  1158. float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
  1159. float y = sinf(x);//*cosf(x*1.1f+1.0f);
  1160. float z = (y+1.0f)*0.5f; // scale to [0..1]
  1161. z += (frand()-0.5f)*(randomness/n_vocab);
  1162. z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
  1163. int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
  1164. ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
  1165. if (i<n_tokens) {
  1166. ggml_set_i32_1d(tokens_input, i, token);
  1167. }
  1168. }
  1169. }
  1170. void get_example_targets_batch(struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
  1171. GGML_ASSERT(tokens_input->n_dims == 2);
  1172. GGML_ASSERT( targets->n_dims == 3);
  1173. int n_tokens = tokens_input->ne[0];
  1174. int n_batch = tokens_input->ne[1];
  1175. GGML_ASSERT(n_tokens == targets->ne[1]);
  1176. GGML_ASSERT(n_batch == targets->ne[2]);
  1177. for (int k=0; k<n_batch; ++k) {
  1178. struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
  1179. tokens_input,
  1180. tokens_input->ne[0],
  1181. k*tokens_input->nb[1]);
  1182. struct ggml_tensor * targets_k = ggml_view_2d(ctx,
  1183. targets,
  1184. targets->ne[0],
  1185. targets->ne[1],
  1186. targets->nb[1],
  1187. k*targets->nb[2]);
  1188. get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
  1189. }
  1190. }
  1191. void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
  1192. int n_tokens = tokens_input->ne[0];
  1193. int n_vocab = targets->ne[0];
  1194. for (int i=0; i<n_tokens-n_shift; ++i) {
  1195. ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
  1196. for (int k=0; k<n_vocab; ++k) {
  1197. ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
  1198. }
  1199. }
  1200. }
  1201. struct ggml_tensor * square_error_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
  1202. // todo: instead of a-b: a[1:]-b[:-1]
  1203. return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
  1204. }
  1205. struct ggml_tensor * cross_entropy_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
  1206. const float eps = 1e-3;
  1207. return
  1208. ggml_sum(ctx,
  1209. ggml_neg(ctx,
  1210. ggml_sum_rows(ctx,
  1211. ggml_mul(ctx,
  1212. ggml_soft_max(ctx, a),
  1213. ggml_log(ctx,
  1214. ggml_add1(ctx,
  1215. ggml_soft_max(ctx, b),
  1216. ggml_new_f32(ctx, eps)))))));
  1217. }
  1218. int main(int argc, char ** argv) {
  1219. if (argc < 1) {
  1220. fprintf(stderr, "usage: %s\n", argv[0]);
  1221. return 1;
  1222. }
  1223. struct ggml_init_params lcparams;
  1224. lcparams.mem_size = 1024ll*1024ll*1024ll;
  1225. lcparams.mem_buffer = NULL;
  1226. lcparams.no_alloc = false;
  1227. struct llama_model model;
  1228. model.hparams.n_vocab = 8;
  1229. model.hparams.n_ctx = 8;
  1230. model.hparams.n_embd = 32;
  1231. model.hparams.n_mult = 2;
  1232. model.hparams.n_head = 8;
  1233. model.hparams.n_layer = 1;
  1234. model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
  1235. // model.hparams.n_embd = 32;
  1236. // model.hparams.n_mult = 2;
  1237. // model.hparams.n_head = 4;
  1238. // model.hparams.n_layer = 8;
  1239. // model.hparams.n_rot = 8;
  1240. model.ctx = ggml_init(lcparams);
  1241. printf("init model\n");
  1242. init_model(&model);
  1243. set_param_model(&model);
  1244. randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1245. /*
  1246. struct llama_model_lora model_lora;
  1247. // model.hparams.n_vocab = 6;
  1248. // model.hparams.n_ctx = 64;
  1249. // model.hparams.n_embd = 128;
  1250. // model.hparams.n_mult = 2;
  1251. // model.hparams.n_head = 8;
  1252. // model.hparams.n_layer = 6;
  1253. // model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  1254. model_lora.hparams.n_vocab = 16;
  1255. model_lora.hparams.n_ctx = 32;
  1256. model_lora.hparams.n_embd = 256;
  1257. model_lora.hparams.n_mult = 2;
  1258. model_lora.hparams.n_head = 16;
  1259. model_lora.hparams.n_layer = 1;
  1260. model_lora.hparams.n_lora = 64;
  1261. model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
  1262. // model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
  1263. // model.hparams.n_embd = 32;
  1264. // model.hparams.n_mult = 2;
  1265. // model.hparams.n_head = 4;
  1266. // model.hparams.n_layer = 8;
  1267. // model.hparams.n_rot = 8;
  1268. model_lora.ctx = ggml_init(lcparams);
  1269. printf("init model_lora\n");
  1270. init_model_lora(&model_lora);
  1271. set_param_model_lora(&model_lora);
  1272. randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1273. */
  1274. int n_batch = 8;
  1275. // key + value cache for the self attention
  1276. struct llama_kv_cache kv_self;
  1277. printf("init_kv_cache\n");
  1278. kv_self.ctx = model.ctx;
  1279. init_kv_cache(&kv_self, &model, n_batch);
  1280. //init_kv_cache_lora(&kv_self, &model_lora);
  1281. size_t compute_size = 1024ll*1024ll*1024ll;
  1282. uint8_t * compute_addr = new uint8_t[compute_size];
  1283. int n_examples = 256;
  1284. int n_tokens = model.hparams.n_ctx;
  1285. int n_vocab = model.hparams.n_vocab;
  1286. for (int ex=0; ex<n_examples; ++ex) {
  1287. struct ggml_init_params params = {
  1288. /*.mem_size =*/ compute_size,
  1289. /*.mem_buffer =*/ compute_addr,
  1290. /*.no_alloc =*/ false,
  1291. };
  1292. struct ggml_context * ctx0 = ggml_init(params);
  1293. struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1294. struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1295. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1296. struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1297. int n_past = 0;
  1298. ggml_cgraph gf = {};
  1299. gf.n_threads = 1;
  1300. get_example_targets_batch(ctx0, 64*ex+0, tokens_input, targets);
  1301. struct ggml_tensor * logits = forward_batch(&model, &kv_self, ctx0, &gf, tokens_input, n_tokens, n_past, n_batch);
  1302. // struct ggml_tensor * e = cross_entropy_loss(ctx0, targets, logits);
  1303. struct ggml_tensor * e = square_error_loss(ctx0, targets, logits);
  1304. ggml_build_forward_expand(&gf, e);
  1305. ggml_graph_compute(ctx0, &gf);
  1306. float error_before_opt = ggml_get_f32_1d(e, 0);
  1307. struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
  1308. struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
  1309. opt_params_adam.print_forward_graph = false;
  1310. opt_params_adam.print_backward_graph = false;
  1311. opt_params_lbfgs.print_forward_graph = false;
  1312. opt_params_lbfgs.print_backward_graph = false;
  1313. opt_params_adam.adam.n_iter = 16;
  1314. opt_params_lbfgs.lbfgs.n_iter = 16;
  1315. // ggml_opt(ctx0, opt_params_adam, e);
  1316. ggml_opt(ctx0, opt_params_lbfgs, e);
  1317. //
  1318. ggml_build_forward_expand(&gf, e);
  1319. ggml_graph_compute(ctx0, &gf);
  1320. float error_after_opt = ggml_get_f32_1d(e, 0);
  1321. if (ex % 8 == 0) {
  1322. printf("Example %d\n", (ex+1));
  1323. printf("error_before_opt: %.2f\n", error_before_opt);
  1324. printf("error_after_opt: %.2f\n", error_after_opt);
  1325. }
  1326. if (ex % 64 == 0) {
  1327. sample_softmax_batch(ctx0, logits, after_opt_probs, after_opt_best_samples);
  1328. // printf("probabilities after optimization:\n");
  1329. // print_matrix(after_opt_probs);
  1330. printf("best samples after optimization:\n");
  1331. print_tokens(after_opt_best_samples, n_vocab);
  1332. }
  1333. ggml_free(ctx0);
  1334. }
  1335. {
  1336. int n_gen = 128;
  1337. int sample_ctx = n_tokens-n_tokens/8;
  1338. printf("Generating %d tokens.\n", n_gen);
  1339. struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
  1340. struct ggml_tensor * targets = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
  1341. get_example_targets(137, tokens_input, targets);
  1342. for (int i=sample_ctx; i<n_tokens; ++i) {
  1343. ggml_set_i32_1d(tokens_input, i, n_vocab/2);
  1344. }
  1345. for (int i=0; i<sample_ctx-1; ++i) {
  1346. print_token(ggml_get_i32_1d(tokens_input, i), n_vocab);
  1347. }
  1348. printf("---\n");
  1349. for (int i=0; i<n_gen; ++i) {
  1350. struct ggml_init_params params = {
  1351. /*.mem_size =*/ compute_size,
  1352. /*.mem_buffer =*/ compute_addr,
  1353. /*.no_alloc =*/ false,
  1354. };
  1355. struct ggml_context * ctx0 = ggml_init(params);
  1356. ggml_cgraph gf = {};
  1357. gf.n_threads = 1;
  1358. int n_past = 0;
  1359. struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, &gf, tokens_input, sample_ctx, n_past);
  1360. ggml_build_forward_expand(&gf, logits);
  1361. ggml_graph_compute(ctx0, &gf);
  1362. struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
  1363. struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
  1364. sample_softmax(logits, probs, best_samples);
  1365. // int sample_at = n_tokens-1;
  1366. int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
  1367. // print_row(probs, sample_at);
  1368. print_token(token, n_vocab);
  1369. lshift_examples(tokens_input, targets, 1);
  1370. ggml_set_i32_1d(tokens_input, 0, 0);
  1371. ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
  1372. ggml_free(ctx0);
  1373. }
  1374. }
  1375. print_matrix(model.tok_embeddings);
  1376. printf("done\n");
  1377. // ggml_free(kv_self.ctx);
  1378. // ggml_free(model_lora.ctx);
  1379. ggml_free(model.ctx);
  1380. return 0;
  1381. }