baby-llama.cpp 61 KB

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