baby-llama.cpp 65 KB

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