baby-llama.cpp 61 KB

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