baby-llama.cpp 65 KB

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