baby-llama.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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 = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  452. // KQ_masked = mask_past(KQ_scaled)
  453. // KQ_masked shape [n_past + N, N, n_head, 1]
  454. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  455. // KQ = soft_max(KQ_masked)
  456. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  457. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  458. // split cached V into n_head heads
  459. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  460. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  461. struct ggml_tensor * V =
  462. ggml_view_3d(ctx0, vc,
  463. n_past + N, n_embd/n_head, n_head,
  464. n_ctx*ggml_element_size(vc),
  465. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  466. il*n_ctx*ggml_element_size(vc)*n_embd);
  467. // KQV shape [n_embd/n_head, N, n_head, 1]
  468. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  469. // KQV_merged = KQV.permute(0, 2, 1, 3)
  470. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  471. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  472. // KQV_merged shape
  473. // cur = KQV_merged.contiguous().view(n_embd, N)
  474. // cur shape [n_embd,N,1,1]
  475. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  476. // cur = ggml_cpy(ctx0,
  477. // KQV_merged,
  478. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  479. // projection (no bias)
  480. // cur shape [n_embd,N,1,1]
  481. cur = ggml_mul_mat(ctx0,
  482. model->layers[il].wo,
  483. cur);
  484. }
  485. // lctx.use_buf(ctx0, 1);
  486. // inpFF shape [n_embd,N,1,1]
  487. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  488. // feed-forward network
  489. {
  490. // norm
  491. {
  492. // cur shape [n_embd,N,1,1]
  493. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  494. // cur = ffn_norm*cur
  495. // cur shape [n_embd,N,1,1]
  496. cur = ggml_mul(ctx0,
  497. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  498. cur);
  499. }
  500. // tmp shape [n_ff,N,1,1]
  501. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  502. model->layers[il].w3,
  503. cur);
  504. // cur shape [n_ff,N,1,1]
  505. cur = ggml_mul_mat(ctx0,
  506. model->layers[il].w1,
  507. cur);
  508. // SILU activation
  509. // cur shape [n_ff,N,1,1]
  510. cur = ggml_silu(ctx0, cur);
  511. // cur shape [n_ff,N,1,1]
  512. cur = ggml_mul(ctx0, cur, tmp);
  513. // cur shape [n_embd,N,1,1]
  514. cur = ggml_mul_mat(ctx0,
  515. model->layers[il].w2,
  516. cur);
  517. }
  518. // cur shape [n_embd,N,1,1]
  519. cur = ggml_add(ctx0, cur, inpFF);
  520. // input for next layer
  521. // inpL shape [n_embd,N,1,1]
  522. inpL = cur;
  523. }
  524. // norm
  525. {
  526. // inpL shape [n_embd,N,1,1]
  527. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  528. // inpL = norm*inpL
  529. // inpL shape [n_embd,N,1,1]
  530. inpL = ggml_mul(ctx0,
  531. ggml_repeat(ctx0, model->norm, inpL),
  532. inpL);
  533. //embeddings = inpL;
  534. }
  535. // lm_head
  536. // inpL shape [n_vocab,N,1,1]
  537. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  538. // run the computation
  539. ggml_build_forward_expand(gf, inpL);
  540. return inpL;
  541. }
  542. static struct ggml_tensor * forward_batch(
  543. struct llama_model * model,
  544. struct llama_kv_cache * cache,
  545. struct ggml_context * ctx0,
  546. struct ggml_cgraph * gf,
  547. struct ggml_tensor * tokens_input,
  548. const int n_tokens,
  549. const int n_past,
  550. const int n_batch
  551. ) {
  552. const int N = n_tokens;
  553. struct llama_kv_cache& kv_self = *cache;
  554. const auto & hparams = model->hparams;
  555. const int n_ctx = hparams.n_ctx;
  556. const int n_vocab = hparams.n_vocab;
  557. const int n_embd = hparams.n_embd;
  558. const int n_layer = hparams.n_layer;
  559. const int n_head = hparams.n_head;
  560. const int n_rot = hparams.n_rot;
  561. const int n_ff = get_n_ff(&hparams);
  562. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  563. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  564. struct ggml_tensor * kc = kv_self.k;
  565. struct ggml_tensor * vc = kv_self.v;
  566. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  567. {
  568. int * data = (int *) KQ_pos->data;
  569. for (int i = 0; i < N; ++i) {
  570. data[i] = n_past + i;
  571. }
  572. }
  573. // inpL shape [n_embd,N*n_batch,1]
  574. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  575. assert_shape_2d(inpL, n_embd, N*n_batch);
  576. for (int il = 0; il < n_layer; ++il) {
  577. struct ggml_tensor * inpSA = inpL;
  578. struct ggml_tensor * cur;
  579. // lctx.use_buf(ctx0, 0);
  580. // norm
  581. {
  582. // cur shape [n_embd,N*n_batch,1,1]
  583. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  584. assert_shape_2d(cur, n_embd, N*n_batch);
  585. // cur = attention_norm*cur
  586. cur = ggml_mul(ctx0,
  587. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  588. cur);
  589. assert_shape_2d(cur, n_embd, N*n_batch);
  590. }
  591. // self-attention
  592. {
  593. // compute Q and K and RoPE them
  594. // wq shape [n_embd, n_embd, 1, 1]
  595. // wk shape [n_embd, n_embd, 1, 1]
  596. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  597. // Kcur shape [n_embd/n_head, n_head, N, n_batch]
  598. 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);
  599. 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);
  600. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  601. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  602. // store key and value to memory
  603. {
  604. // compute the transposed [N, n_embd] V matrix
  605. // wv shape [n_embd, n_embd, 1, 1]
  606. // Vcur shape [N, n_embd, n_batch, 1]
  607. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  608. ggml_permute(ctx0,
  609. ggml_reshape_3d(ctx0,
  610. ggml_mul_mat(ctx0,
  611. model->layers[il].wv,
  612. cur),
  613. n_embd, N, n_batch),
  614. 1, 0, 2, 3));
  615. assert_shape_3d(Vcur, N, n_embd, n_batch);
  616. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  617. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  618. // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
  619. // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
  620. /* {
  621. 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));
  622. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  623. ( n_ctx)*ggml_element_size(kv_self.v),
  624. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  625. // important: storing RoPE-ed version of K in the KV cache!
  626. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  627. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  628. } //*/
  629. kc = ggml_set_2d(ctx0, kc,
  630. ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
  631. ggml_element_size(kc)*n_embd*n_ctx,
  632. (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
  633. vc = ggml_set_2d(ctx0, vc,
  634. ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
  635. ggml_element_size(vc)*n_ctx*n_embd,
  636. ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
  637. assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
  638. assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
  639. }
  640. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  641. // Q shape [n_embd/n_head, N, n_head, n_batch]
  642. struct ggml_tensor * Q =
  643. ggml_permute(ctx0,
  644. Qcur,
  645. 0, 2, 1, 3);
  646. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  647. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  648. // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
  649. struct ggml_tensor * K =
  650. ggml_permute(ctx0,
  651. ggml_reshape_4d(ctx0,
  652. ggml_view_3d(ctx0,
  653. kc,
  654. n_embd,
  655. (n_past + N),
  656. n_batch,
  657. n_embd*ggml_element_size(kc),
  658. n_ctx*n_embd*ggml_element_size(kc),
  659. il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
  660. n_embd/n_head, n_head, n_past + N, n_batch),
  661. 0, 2, 1, 3);
  662. assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
  663. // K * Q
  664. // KQ shape [n_past + N, N, n_head, n_batch]
  665. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  666. assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
  667. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  668. // KQ_scaled shape [n_past + N, N, n_head, n_batch]
  669. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  670. assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
  671. // KQ_masked = mask_past(KQ_scaled)
  672. // KQ_masked shape [n_past + N, N, n_head, n_batch]
  673. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  674. assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
  675. // KQ = soft_max(KQ_masked)
  676. // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
  677. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  678. assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
  679. // split cached V into n_head heads
  680. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  681. // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
  682. struct ggml_tensor * V =
  683. ggml_view_4d(ctx0, vc,
  684. n_past + N, n_embd/n_head, n_head, n_batch,
  685. ggml_element_size(vc)*n_ctx,
  686. ggml_element_size(vc)*n_ctx*n_embd/n_head,
  687. ggml_element_size(vc)*n_ctx*n_embd,
  688. il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
  689. assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
  690. // KQV shape [n_embd/n_head, N, n_head, n_batch]
  691. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  692. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  693. // KQV_merged = KQV.permute(0, 2, 1, 3)
  694. // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
  695. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  696. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  697. // KQV_merged shape
  698. // cur = KQV_merged.contiguous().view(n_embd, N)
  699. // cur shape [n_embd,N*n_batch,1,1]
  700. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  701. assert_shape_2d(cur, n_embd, N*n_batch);
  702. // cur = ggml_cpy(ctx0,
  703. // KQV_merged,
  704. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  705. // projection (no bias)
  706. // cur shape [n_embd,N*n_batch,1,1]
  707. cur = ggml_mul_mat(ctx0,
  708. model->layers[il].wo,
  709. cur);
  710. assert_shape_2d(cur, n_embd, N*n_batch);
  711. }
  712. // lctx.use_buf(ctx0, 1);
  713. // inpFF shape [n_embd,N*n_batch,1,1]
  714. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  715. assert_shape_2d(inpFF, n_embd, N*n_batch);
  716. // feed-forward network
  717. {
  718. // norm
  719. {
  720. // cur shape [n_embd,N*n_batch,1,1]
  721. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  722. assert_shape_2d(cur, n_embd, N*n_batch);
  723. // cur = ffn_norm*cur
  724. // cur shape [n_embd,N*n_batch,1,1]
  725. cur = ggml_mul(ctx0,
  726. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  727. cur);
  728. assert_shape_2d(cur, n_embd, N*n_batch);
  729. }
  730. // tmp shape [n_ff,N*n_batch,1,1]
  731. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  732. model->layers[il].w3,
  733. cur);
  734. assert_shape_2d(tmp, n_ff, N*n_batch);
  735. // cur shape [n_ff,N*n_batch,1,1]
  736. cur = ggml_mul_mat(ctx0,
  737. model->layers[il].w1,
  738. cur);
  739. assert_shape_2d(cur, n_ff, N*n_batch);
  740. // SILU activation
  741. // cur shape [n_ff,N*n_batch,1,1]
  742. cur = ggml_silu(ctx0, cur);
  743. assert_shape_2d(cur, n_ff, N*n_batch);
  744. // cur shape [n_ff,N*n_batch,1,1]
  745. cur = ggml_mul(ctx0, cur, tmp);
  746. assert_shape_2d(cur, n_ff, N*n_batch);
  747. // cur shape [n_embd,N*n_batch,1,1]
  748. cur = ggml_mul_mat(ctx0,
  749. model->layers[il].w2,
  750. cur);
  751. assert_shape_2d(cur, n_embd, N*n_batch);
  752. }
  753. // cur shape [n_embd,N*n_batch,1,1]
  754. cur = ggml_add(ctx0, cur, inpFF);
  755. assert_shape_2d(cur, n_embd, N*n_batch);
  756. // input for next layer
  757. // inpL shape [n_embd,N*n_batch,1,1]
  758. inpL = cur;
  759. assert_shape_2d(inpL, n_embd, N*n_batch);
  760. }
  761. // norm
  762. {
  763. // inpL shape [n_embd,N*n_batch,1,1]
  764. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  765. assert_shape_2d(inpL, n_embd, N*n_batch);
  766. // inpL = norm*inpL
  767. // inpL shape [n_embd,N*n_batch,1,1]
  768. inpL = ggml_mul(ctx0,
  769. ggml_repeat(ctx0, model->norm, inpL),
  770. inpL);
  771. assert_shape_2d(inpL, n_embd, N*n_batch);
  772. //embeddings = inpL;
  773. }
  774. // lm_head
  775. // inpL shape [n_vocab,N*n_batch,1,1]
  776. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  777. assert_shape_2d(inpL, n_vocab, N*n_batch);
  778. {
  779. // inpL shape [n_vocab,N,n_batch,1]
  780. inpL = ggml_reshape_3d(ctx0,
  781. inpL,
  782. n_vocab, N, n_batch);
  783. assert_shape_3d(inpL, n_vocab, N, n_batch);
  784. }
  785. // run the computation
  786. ggml_build_forward_expand(gf, inpL);
  787. return inpL;
  788. }
  789. static struct ggml_tensor * forward_lora(
  790. struct llama_model_lora * model,
  791. struct llama_kv_cache * cache,
  792. struct ggml_context * ctx0,
  793. struct ggml_cgraph * gf,
  794. struct ggml_tensor * tokens_input,
  795. const int n_tokens,
  796. const int n_past
  797. ) {
  798. const int N = n_tokens;
  799. struct llama_kv_cache& kv_self = *cache;
  800. const auto & hparams = model->hparams;
  801. const int n_ctx = hparams.n_ctx;
  802. const int n_embd = hparams.n_embd;
  803. const int n_layer = hparams.n_layer;
  804. const int n_head = hparams.n_head;
  805. const int n_rot = hparams.n_rot;
  806. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  807. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  808. struct ggml_tensor * kc = kv_self.k;
  809. struct ggml_tensor * vc = kv_self.v;
  810. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  811. {
  812. int * data = (int *) KQ_pos->data;
  813. for (int i = 0; i < N; ++i) {
  814. data[i] = n_past + i;
  815. }
  816. }
  817. // inpL shape [n_embd,N,1,1]
  818. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  819. for (int il = 0; il < n_layer; ++il) {
  820. struct ggml_tensor * inpSA = inpL;
  821. struct ggml_tensor * cur;
  822. // norm
  823. {
  824. // cur shape [n_embd,N,1,1]
  825. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  826. // cur = attention_norm*cur
  827. cur = ggml_mul(ctx0,
  828. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  829. cur);
  830. }
  831. // self-attention
  832. {
  833. // compute Q and K and RoPE them
  834. // wq shape [n_embd, n_embd, 1, 1]
  835. // wk shape [n_embd, n_embd, 1, 1]
  836. // Qcur shape [n_embd/n_head, n_head, N, 1]
  837. // Kcur shape [n_embd/n_head, n_head, N, 1]
  838. struct ggml_tensor * Qcur = ggml_rope(ctx0,
  839. ggml_reshape_3d(ctx0,
  840. ggml_mul_mat(ctx0,
  841. model->layers[il].wqa,
  842. ggml_mul_mat(ctx0,
  843. model->layers[il].wqb,
  844. cur)),
  845. n_embd/n_head, n_head, N),
  846. KQ_pos, n_rot, 0, 0);
  847. struct ggml_tensor * Kcur = ggml_rope(ctx0,
  848. ggml_reshape_3d(ctx0,
  849. ggml_mul_mat(ctx0,
  850. model->layers[il].wka,
  851. ggml_mul_mat(ctx0,
  852. model->layers[il].wkb,
  853. cur)),
  854. n_embd/n_head, n_head, N),
  855. KQ_pos, n_rot, 0, 0);
  856. // store key and value to memory
  857. {
  858. // compute the transposed [N, n_embd] V matrix
  859. // wv shape [n_embd, n_embd, 1, 1]
  860. // Vcur shape [n_embd, N, 1, 1]
  861. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  862. ggml_transpose(ctx0,
  863. ggml_reshape_2d(ctx0,
  864. ggml_mul_mat(ctx0,
  865. model->layers[il].wva,
  866. ggml_mul_mat(ctx0,
  867. model->layers[il].wvb,
  868. cur)),
  869. n_embd, N)));
  870. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  871. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  872. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  873. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  874. /* {
  875. 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));
  876. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  877. ( n_ctx)*ggml_element_size(kv_self.v),
  878. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  879. // important: storing RoPE-ed version of K in the KV cache!
  880. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  881. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  882. } //*/
  883. 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));
  884. vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  885. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  886. }
  887. // Qcur shape [n_embd/n_head, n_head, N, 1]
  888. // Q shape [n_embd/n_head, N, n_head, 1]
  889. struct ggml_tensor * Q =
  890. ggml_permute(ctx0,
  891. Qcur,
  892. 0, 2, 1, 3);
  893. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  894. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  895. struct ggml_tensor * K =
  896. ggml_permute(ctx0,
  897. ggml_reshape_3d(ctx0,
  898. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  899. n_embd/n_head, n_head, n_past + N),
  900. 0, 2, 1, 3);
  901. // K * Q
  902. // KQ shape [n_past + N, N, n_head, 1]
  903. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  904. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  905. // KQ_scaled shape [n_past + N, N, n_head, 1]
  906. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  907. // KQ_masked = mask_past(KQ_scaled)
  908. // KQ_masked shape [n_past + N, N, n_head, 1]
  909. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  910. // KQ = soft_max(KQ_masked)
  911. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  912. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  913. // split cached V into n_head heads
  914. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  915. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  916. struct ggml_tensor * V =
  917. ggml_view_3d(ctx0, vc,
  918. n_past + N, n_embd/n_head, n_head,
  919. n_ctx*ggml_element_size(vc),
  920. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  921. il*n_ctx*ggml_element_size(vc)*n_embd);
  922. // KQV shape [n_embd/n_head, N, n_head, 1]
  923. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  924. // KQV_merged = KQV.permute(0, 2, 1, 3)
  925. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  926. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  927. // KQV_merged shape
  928. // cur = KQV_merged.contiguous().view(n_embd, N)
  929. // cur shape [n_embd,N,1,1]
  930. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  931. // cur = ggml_cpy(ctx0,
  932. // KQV_merged,
  933. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  934. // projection (no bias)
  935. // cur shape [n_embd,N,1,1]
  936. cur = ggml_mul_mat(ctx0,
  937. model->layers[il].woa,
  938. ggml_mul_mat(ctx0,
  939. model->layers[il].wob,
  940. cur));
  941. }
  942. // inpFF shape [n_embd,N,1,1]
  943. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  944. // feed-forward network
  945. {
  946. // norm
  947. {
  948. // cur shape [n_embd,N,1,1]
  949. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  950. // cur = ffn_norm*cur
  951. // cur shape [n_embd,N,1,1]
  952. cur = ggml_mul(ctx0,
  953. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  954. cur);
  955. }
  956. // tmp shape [n_ff,N,1,1]
  957. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  958. model->layers[il].w3,
  959. cur);
  960. // cur shape [n_ff,N,1,1]
  961. cur = ggml_mul_mat(ctx0,
  962. model->layers[il].w1,
  963. cur);
  964. // SILU activation
  965. // cur shape [n_ff,N,1,1]
  966. cur = ggml_silu(ctx0, cur);
  967. // cur shape [n_ff,N,1,1]
  968. cur = ggml_mul(ctx0, cur, tmp);
  969. // cur shape [n_embd,N,1,1]
  970. cur = ggml_mul_mat(ctx0,
  971. model->layers[il].w2,
  972. cur);
  973. }
  974. // cur shape [n_embd,N,1,1]
  975. cur = ggml_add(ctx0, cur, inpFF);
  976. // input for next layer
  977. // inpL shape [n_embd,N,1,1]
  978. inpL = cur;
  979. }
  980. // norm
  981. {
  982. // inpL shape [n_embd,N,1,1]
  983. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  984. // inpL = norm*inpL
  985. // inpL shape [n_embd,N,1,1]
  986. inpL = ggml_mul(ctx0,
  987. ggml_repeat(ctx0, model->norm, inpL),
  988. inpL);
  989. //embeddings = inpL;
  990. }
  991. // lm_head
  992. // inpL shape [n_vocab,N,1,1]
  993. inpL = ggml_mul_mat(ctx0,
  994. model->outputa,
  995. ggml_mul_mat(ctx0,
  996. model->outputb,
  997. inpL));
  998. // ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  999. // run the computation
  1000. ggml_build_forward_expand(gf, inpL);
  1001. return inpL;
  1002. }
  1003. static void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
  1004. assert(ggml_is_matrix(logits));
  1005. assert(ggml_is_matrix(probs));
  1006. assert(ggml_is_vector(best_samples));
  1007. assert(logits->ne[1] == best_samples->ne[0]);
  1008. assert(logits->ne[0] == probs->ne[0]);
  1009. assert(logits->ne[1] == probs->ne[1]);
  1010. for (int i = 0; i < logits->ne[1]; ++i) {
  1011. float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
  1012. ggml_set_i32_1d(best_samples, i, 0);
  1013. for (int k = 0; k < logits->ne[0]; ++k) {
  1014. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1015. if (logit > max_logit) {
  1016. max_logit = logit;
  1017. ggml_set_i32_1d(best_samples, i, k);
  1018. }
  1019. }
  1020. float psum = 0;
  1021. for (int k = 0; k < logits->ne[0]; ++k) {
  1022. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1023. float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
  1024. psum += p;
  1025. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
  1026. }
  1027. for (int k = 0; k < logits->ne[0]; ++k) {
  1028. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1029. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
  1030. }
  1031. }
  1032. }
  1033. static void sample_softmax_batch(
  1034. struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs,
  1035. struct ggml_tensor * best_samples
  1036. ) {
  1037. GGML_ASSERT(ggml_is_matrix(best_samples));
  1038. GGML_ASSERT(ggml_is_3d(logits));
  1039. GGML_ASSERT(ggml_is_3d(probs));
  1040. int n_tokens = best_samples->ne[0];
  1041. int n_batch = best_samples->ne[1];
  1042. int n_vocab = logits->ne[0];
  1043. GGML_ASSERT(n_tokens == logits->ne[1]);
  1044. GGML_ASSERT(n_batch == logits->ne[2]);
  1045. GGML_ASSERT(n_vocab == probs->ne[0]);
  1046. GGML_ASSERT(n_tokens == probs->ne[1]);
  1047. GGML_ASSERT(n_batch == probs->ne[2]);
  1048. for (int k = 0; k < n_batch; ++k) {
  1049. struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
  1050. best_samples,
  1051. best_samples->ne[0],
  1052. k*best_samples->nb[1]);
  1053. struct ggml_tensor * logits_k = ggml_view_2d(ctx,
  1054. logits,
  1055. logits->ne[0],
  1056. logits->ne[1],
  1057. logits->nb[1],
  1058. k*logits->nb[2]);
  1059. struct ggml_tensor * probs_k = ggml_view_2d(ctx,
  1060. probs,
  1061. probs->ne[0],
  1062. probs->ne[1],
  1063. probs->nb[1],
  1064. k*probs->nb[2]);
  1065. sample_softmax(logits_k, probs_k, best_samples_k);
  1066. }
  1067. }
  1068. static void print_row(struct ggml_tensor * probs, int i) {
  1069. for (int k = 0; k < probs->ne[0]; ++k) {
  1070. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1071. printf(" %.2f", p);
  1072. }
  1073. printf("\n");
  1074. }
  1075. static void print_matrix(struct ggml_tensor * probs) {
  1076. assert(ggml_is_matrix(probs));
  1077. for (int i = 0; i < probs->ne[1]; ++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. }
  1085. static void print_token(int token, int n_vocab) {
  1086. for (int k = 0; k < token; ++k) {
  1087. printf(" ");
  1088. }
  1089. printf("X");
  1090. for (int k = token+1; k < n_vocab; ++k) {
  1091. printf(" ");
  1092. }
  1093. printf("\n");
  1094. }
  1095. static void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
  1096. for (int i=0; i<tokens->ne[0]; ++i) {
  1097. int token = ggml_get_i32_1d(tokens, i);
  1098. print_token(token, n_vocab);
  1099. }
  1100. }
  1101. static void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
  1102. int n_tokens = tokens_input->ne[0];
  1103. int n_vocab = targets->ne[0];
  1104. float randomness = 0.0f;
  1105. // ggml_set_zero(targets);
  1106. ggml_set_f32(targets, -1.0f);
  1107. ggml_set_i32_1d(tokens_input, 0, 0);
  1108. for (int i=1; i<n_tokens+1; ++i) {
  1109. float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
  1110. float y = sinf(x);//*cosf(x*1.1f+1.0f);
  1111. float z = (y+1.0f)*0.5f; // scale to [0..1]
  1112. z += (frand()-0.5f)*(randomness/n_vocab);
  1113. z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
  1114. int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
  1115. ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
  1116. if (i<n_tokens) {
  1117. ggml_set_i32_1d(tokens_input, i, token);
  1118. }
  1119. }
  1120. }
  1121. static void get_example_targets_batch(
  1122. struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets
  1123. ) {
  1124. GGML_ASSERT(ggml_is_matrix(tokens_input));
  1125. GGML_ASSERT(ggml_is_3d(targets));
  1126. int n_tokens = tokens_input->ne[0];
  1127. int n_batch = tokens_input->ne[1];
  1128. GGML_ASSERT(n_tokens == targets->ne[1]);
  1129. GGML_ASSERT(n_batch == targets->ne[2]);
  1130. for (int k=0; k<n_batch; ++k) {
  1131. struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
  1132. tokens_input,
  1133. tokens_input->ne[0],
  1134. k*tokens_input->nb[1]);
  1135. struct ggml_tensor * targets_k = ggml_view_2d(ctx,
  1136. targets,
  1137. targets->ne[0],
  1138. targets->ne[1],
  1139. targets->nb[1],
  1140. k*targets->nb[2]);
  1141. get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
  1142. }
  1143. }
  1144. static void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
  1145. int n_tokens = tokens_input->ne[0];
  1146. int n_vocab = targets->ne[0];
  1147. for (int i=0; i<n_tokens-n_shift; ++i) {
  1148. ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
  1149. for (int k=0; k<n_vocab; ++k) {
  1150. ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
  1151. }
  1152. }
  1153. }
  1154. static struct ggml_tensor * square_error_loss(
  1155. struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
  1156. ) {
  1157. // todo: instead of a-b: a[1:]-b[:-1]
  1158. return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
  1159. }
  1160. static struct ggml_tensor * cross_entropy_loss(
  1161. struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
  1162. ) {
  1163. const float eps = 1e-3f;
  1164. return
  1165. ggml_sum(ctx,
  1166. ggml_neg(ctx,
  1167. ggml_sum_rows(ctx,
  1168. ggml_mul(ctx,
  1169. ggml_soft_max(ctx, a),
  1170. ggml_log(ctx,
  1171. ggml_add1(ctx,
  1172. ggml_soft_max(ctx, b),
  1173. ggml_new_f32(ctx, eps)))))));
  1174. }
  1175. int main(int argc, char ** argv) {
  1176. if (argc < 1) {
  1177. fprintf(stderr, "usage: %s\n", argv[0]);
  1178. return 1;
  1179. }
  1180. struct ggml_init_params lcparams;
  1181. lcparams.mem_size = 1024ll*1024ll*1024ll;
  1182. lcparams.mem_buffer = NULL;
  1183. lcparams.no_alloc = false;
  1184. struct llama_model model;
  1185. model.hparams.n_vocab = 8;
  1186. model.hparams.n_ctx = 8;
  1187. model.hparams.n_embd = 32;
  1188. model.hparams.n_mult = 2;
  1189. model.hparams.n_head = 8;
  1190. model.hparams.n_layer = 1;
  1191. model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
  1192. // model.hparams.n_embd = 32;
  1193. // model.hparams.n_mult = 2;
  1194. // model.hparams.n_head = 4;
  1195. // model.hparams.n_layer = 8;
  1196. // model.hparams.n_rot = 8;
  1197. model.ctx = ggml_init(lcparams);
  1198. printf("init model\n");
  1199. init_model(&model);
  1200. set_param_model(&model);
  1201. randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1202. /*
  1203. struct llama_model_lora model_lora;
  1204. // model.hparams.n_vocab = 6;
  1205. // model.hparams.n_ctx = 64;
  1206. // model.hparams.n_embd = 128;
  1207. // model.hparams.n_mult = 2;
  1208. // model.hparams.n_head = 8;
  1209. // model.hparams.n_layer = 6;
  1210. // model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  1211. model_lora.hparams.n_vocab = 16;
  1212. model_lora.hparams.n_ctx = 32;
  1213. model_lora.hparams.n_embd = 256;
  1214. model_lora.hparams.n_mult = 2;
  1215. model_lora.hparams.n_head = 16;
  1216. model_lora.hparams.n_layer = 1;
  1217. model_lora.hparams.n_lora = 64;
  1218. model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
  1219. // model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
  1220. // model.hparams.n_embd = 32;
  1221. // model.hparams.n_mult = 2;
  1222. // model.hparams.n_head = 4;
  1223. // model.hparams.n_layer = 8;
  1224. // model.hparams.n_rot = 8;
  1225. model_lora.ctx = ggml_init(lcparams);
  1226. printf("init model_lora\n");
  1227. init_model_lora(&model_lora);
  1228. set_param_model_lora(&model_lora);
  1229. randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1230. */
  1231. int n_batch = 8;
  1232. // key + value cache for the self attention
  1233. struct llama_kv_cache kv_self;
  1234. printf("init_kv_cache\n");
  1235. kv_self.ctx = model.ctx;
  1236. init_kv_cache(&kv_self, &model, n_batch);
  1237. //init_kv_cache_lora(&kv_self, &model_lora);
  1238. size_t compute_size = 1024ll*1024ll*1024ll;
  1239. uint8_t * compute_addr = new uint8_t[compute_size];
  1240. int n_examples = 256;
  1241. int n_tokens = model.hparams.n_ctx;
  1242. int n_vocab = model.hparams.n_vocab;
  1243. std::vector<uint8_t> work_buffer;
  1244. for (int ex=0; ex<n_examples; ++ex) {
  1245. struct ggml_init_params params = {
  1246. /*.mem_size =*/ compute_size,
  1247. /*.mem_buffer =*/ compute_addr,
  1248. /*.no_alloc =*/ false,
  1249. };
  1250. struct ggml_context * ctx0 = ggml_init(params);
  1251. struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1252. struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1253. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1254. struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1255. int n_past = 0;
  1256. ggml_cgraph gf = {};
  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_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. ggml_cgraph gf = {};
  1309. int n_past = 0;
  1310. struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, &gf, tokens_input, sample_ctx, n_past);
  1311. ggml_build_forward_expand(&gf, logits);
  1312. ggml_graph_compute_helper(work_buffer, &gf, /*n_threads*/ 1);
  1313. struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
  1314. struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
  1315. sample_softmax(logits, probs, best_samples);
  1316. // int sample_at = n_tokens-1;
  1317. int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
  1318. // print_row(probs, sample_at);
  1319. print_token(token, n_vocab);
  1320. lshift_examples(tokens_input, targets, 1);
  1321. ggml_set_i32_1d(tokens_input, 0, 0);
  1322. ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
  1323. ggml_free(ctx0);
  1324. }
  1325. }
  1326. print_matrix(model.tok_embeddings);
  1327. printf("done\n");
  1328. // ggml_free(kv_self.ctx);
  1329. // ggml_free(model_lora.ctx);
  1330. ggml_free(model.ctx);
  1331. return 0;
  1332. }