train-text-from-scratch.cpp 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399
  1. #include "ggml.h"
  2. #include "llama.h"
  3. #include <unordered_map>
  4. #include <vector>
  5. #include <cassert>
  6. #include <climits>
  7. #include <cstring>
  8. #include <cstdarg>
  9. #include <ctime>
  10. #include <random>
  11. #include <stdexcept>
  12. #include <algorithm>
  13. #include <string>
  14. struct random_normal_distribution {
  15. std::mt19937 gen;
  16. std::normal_distribution<float> rd;
  17. float min;
  18. float max;
  19. };
  20. struct random_uniform_distribution {
  21. std::mt19937 gen;
  22. std::uniform_real_distribution<float> rd;
  23. };
  24. void init_random_normal_distribution(struct random_normal_distribution * rnd, int seed, float mean, float std, float min, float max) {
  25. rnd->gen = std::mt19937(seed);
  26. rnd->rd = std::normal_distribution<float>{mean, std};
  27. rnd->min = min;
  28. rnd->max = max;
  29. }
  30. void init_random_uniform_distribution(struct random_uniform_distribution * rnd, int seed, float min, float max) {
  31. rnd->gen = std::mt19937(seed);
  32. rnd->rd = std::uniform_real_distribution<float>{min, max};
  33. }
  34. int clamp(const int v, const int min, const int max) {
  35. return ((v < min) ? (min) : (v > max) ? (max) : v);
  36. }
  37. float fclamp(const float v, const float min, const float max) {
  38. return ((v < min) ? (min) : (v > max) ? (max) : v);
  39. }
  40. float frand() {
  41. return (float)rand()/(float)RAND_MAX;
  42. }
  43. float frand_normal(struct random_normal_distribution * rnd) {
  44. return fclamp(rnd->rd(rnd->gen), rnd->min, rnd->max);
  45. }
  46. float frand_uniform(struct random_uniform_distribution * rnd) {
  47. return rnd->rd(rnd->gen);
  48. }
  49. struct ggml_tensor * randomize_tensor_normal(struct ggml_tensor * tensor, struct random_normal_distribution * rnd) {
  50. float scale = 1.0f; // xavier
  51. switch (tensor->n_dims) {
  52. case 1:
  53. scale /= sqrtf(tensor->ne[0]);
  54. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  55. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  56. *dst = scale * frand_normal(rnd);
  57. }
  58. break;
  59. case 2:
  60. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  61. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  62. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  63. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  64. *dst = scale * frand_normal(rnd);
  65. }
  66. }
  67. break;
  68. case 3:
  69. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  70. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  71. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  72. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  73. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  74. *dst = scale * frand_normal(rnd);
  75. }
  76. }
  77. }
  78. break;
  79. case 4:
  80. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  81. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  82. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  83. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  84. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  85. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  86. *dst = scale * frand_normal(rnd);
  87. }
  88. }
  89. }
  90. }
  91. break;
  92. default:
  93. assert(false);
  94. };
  95. return tensor;
  96. }
  97. struct ggml_tensor * randomize_tensor_uniform(struct ggml_tensor * tensor, struct random_uniform_distribution * rnd) {
  98. switch (tensor->n_dims) {
  99. case 1:
  100. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  101. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  102. *dst = frand_uniform(rnd);
  103. }
  104. break;
  105. case 2:
  106. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  107. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  108. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  109. *dst = frand_uniform(rnd);
  110. }
  111. }
  112. break;
  113. case 3:
  114. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  115. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  116. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  117. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  118. *dst = frand_uniform(rnd);
  119. }
  120. }
  121. }
  122. break;
  123. case 4:
  124. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  125. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  126. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  127. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  128. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  129. *dst = frand_uniform(rnd);
  130. }
  131. }
  132. }
  133. }
  134. break;
  135. default:
  136. assert(false);
  137. };
  138. return tensor;
  139. }
  140. struct llama_vocab {
  141. using id = int32_t;
  142. using token = std::string;
  143. struct token_score {
  144. token tok;
  145. float score;
  146. };
  147. std::unordered_map<token, id> token_to_id;
  148. std::vector<token_score> id_to_token;
  149. };
  150. struct my_llama_hparams {
  151. uint32_t n_vocab = 32000;
  152. uint32_t n_ctx = 512; // this is provided as user input?
  153. uint32_t n_embd = 4096;
  154. uint32_t n_mult = 4;
  155. uint32_t n_head = 32;
  156. uint32_t n_layer = 32;
  157. uint32_t n_rot = 64;
  158. bool operator!=(const my_llama_hparams& other) const {
  159. return memcmp(this, &other, sizeof(my_llama_hparams));
  160. }
  161. };
  162. struct my_llama_layer {
  163. // normalization
  164. struct ggml_tensor * attention_norm;
  165. // attention
  166. struct ggml_tensor * wq;
  167. struct ggml_tensor * wk;
  168. struct ggml_tensor * wv;
  169. struct ggml_tensor * wo;
  170. // normalization
  171. struct ggml_tensor * ffn_norm;
  172. // ff
  173. struct ggml_tensor * w1;
  174. struct ggml_tensor * w2;
  175. struct ggml_tensor * w3;
  176. };
  177. struct my_llama_kv_cache {
  178. struct ggml_context * ctx = NULL;
  179. struct ggml_tensor * k;
  180. struct ggml_tensor * v;
  181. // llama_ctx_buffer buf;
  182. int n; // number of tokens currently in the cache
  183. };
  184. struct my_llama_model {
  185. struct ggml_context * ctx = NULL;
  186. my_llama_hparams hparams;
  187. struct ggml_tensor * tok_embeddings;
  188. struct ggml_tensor * norm;
  189. struct ggml_tensor * output;
  190. std::vector<my_llama_layer> layers;
  191. uint32_t train_its = 0;
  192. uint32_t train_samples = 0;
  193. uint32_t train_tokens = 0;
  194. };
  195. uint32_t get_n_ff(const struct my_llama_hparams* hparams) {
  196. const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
  197. return n_ff;
  198. }
  199. void print_params(struct my_llama_hparams * params) {
  200. printf("%s: n_vocab: %d\n", __func__, params->n_vocab);
  201. printf("%s: n_ctx: %d\n", __func__, params->n_ctx);
  202. printf("%s: n_embd: %d\n", __func__, params->n_embd);
  203. printf("%s: n_mult: %d\n", __func__, params->n_mult);
  204. printf("%s: n_head: %d\n", __func__, params->n_head);
  205. printf("%s: n_ff: %d\n", __func__, get_n_ff(params));
  206. printf("%s: n_layer: %d\n", __func__, params->n_layer);
  207. printf("%s: n_rot: %d\n", __func__, params->n_rot);
  208. }
  209. void init_model(struct my_llama_model * model) {
  210. const auto & hparams = model->hparams;
  211. const uint32_t n_embd = hparams.n_embd;
  212. const uint32_t n_layer = hparams.n_layer;
  213. const uint32_t n_vocab = hparams.n_vocab;
  214. const uint32_t n_ff = get_n_ff(&hparams);
  215. struct ggml_context * ctx = model->ctx;
  216. model->train_its = 0;
  217. model->train_samples = 0;
  218. model->train_tokens = 0;
  219. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  220. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  221. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  222. ggml_set_name(model->tok_embeddings, "tok_embeddings.weight");
  223. ggml_set_name(model->norm, "norm.weight");
  224. ggml_set_name(model->output, "output.weight");
  225. model->layers.resize(n_layer);
  226. for (uint32_t i = 0; i < n_layer; ++i) {
  227. auto & layer = model->layers[i];
  228. std::string layers_i = "layers." + std::to_string(i);
  229. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  230. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  231. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  232. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  233. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  234. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  235. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  236. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd);
  237. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  238. ggml_set_name(layer.attention_norm, (layers_i + ".attention_norm.weight").c_str());
  239. ggml_set_name(layer.wq, (layers_i + ".attention.wq.weight").c_str());
  240. ggml_set_name(layer.wk, (layers_i + ".attention.wk.weight").c_str());
  241. ggml_set_name(layer.wv, (layers_i + ".attention.wv.weight").c_str());
  242. ggml_set_name(layer.wo, (layers_i + ".attention.wo.weight").c_str());
  243. ggml_set_name(layer.ffn_norm, (layers_i + ".ffn_norm.weight").c_str());
  244. // 'layers.10.feed_forward.w1.weight' has length of 32.
  245. // ggml_tensor->name only has 32 characters, but we need one more for the '\0' terminator.
  246. // ggml_set_name will set the last character to '\0', so we can only store 'layers.10.feed_forward.w1.weigh'.
  247. // when saving llama compatible model the tensors names will miss a character.
  248. // ggml_set_name(layer.w1, (layers_i + ".feed_forward.w1.weight").c_str());
  249. // ggml_set_name(layer.w2, (layers_i + ".feed_forward.w2.weight").c_str());
  250. // ggml_set_name(layer.w3, (layers_i + ".feed_forward.w3.weight").c_str());
  251. strncpy(layer.w1->name, (layers_i + ".feed_forward.w1.weight").c_str(), sizeof(layer.w1->name));
  252. strncpy(layer.w2->name, (layers_i + ".feed_forward.w2.weight").c_str(), sizeof(layer.w2->name));
  253. strncpy(layer.w3->name, (layers_i + ".feed_forward.w3.weight").c_str(), sizeof(layer.w3->name));
  254. layer.w1->padding[0] = 0;
  255. layer.w2->padding[0] = 0;
  256. layer.w3->padding[0] = 0;
  257. }
  258. }
  259. void set_param_model(struct my_llama_model * model) {
  260. const auto& hparams = model->hparams;
  261. const uint32_t n_layer = hparams.n_layer;
  262. struct ggml_context* ctx = model->ctx;
  263. ggml_set_param(ctx, model->tok_embeddings);
  264. ggml_set_param(ctx, model->norm);
  265. ggml_set_param(ctx, model->output);
  266. for (uint32_t i = 0; i < n_layer; ++i) {
  267. auto & layer = model->layers[i];
  268. ggml_set_param(ctx, layer.attention_norm);
  269. ggml_set_param(ctx, layer.wq);
  270. ggml_set_param(ctx, layer.wk);
  271. ggml_set_param(ctx, layer.wv);
  272. ggml_set_param(ctx, layer.wo);
  273. ggml_set_param(ctx, layer.ffn_norm);
  274. ggml_set_param(ctx, layer.w1);
  275. ggml_set_param(ctx, layer.w2);
  276. ggml_set_param(ctx, layer.w3);
  277. }
  278. }
  279. void randomize_model(struct my_llama_model * model, int seed, float mean, float std, float min, float max) {
  280. const auto & hparams = model->hparams;
  281. const uint32_t n_layer = hparams.n_layer;
  282. struct random_normal_distribution rnd;
  283. init_random_normal_distribution(&rnd, seed, mean, std, min, max);
  284. randomize_tensor_normal(model->tok_embeddings, &rnd);
  285. randomize_tensor_normal(model->norm, &rnd);
  286. randomize_tensor_normal(model->output, &rnd);
  287. for (uint32_t i = 0; i < n_layer; ++i) {
  288. auto & layer = model->layers[i];
  289. randomize_tensor_normal(layer.attention_norm, &rnd);
  290. randomize_tensor_normal(layer.wq, &rnd);
  291. randomize_tensor_normal(layer.wk, &rnd);
  292. randomize_tensor_normal(layer.wv, &rnd);
  293. randomize_tensor_normal(layer.wo, &rnd);
  294. randomize_tensor_normal(layer.ffn_norm, &rnd);
  295. randomize_tensor_normal(layer.w1, &rnd);
  296. randomize_tensor_normal(layer.w2, &rnd);
  297. randomize_tensor_normal(layer.w3, &rnd);
  298. }
  299. }
  300. bool init_kv_cache(struct my_llama_kv_cache* cache, struct my_llama_model * model, int n_batch) {
  301. const auto & hparams = model->hparams;
  302. const uint32_t n_ctx = hparams.n_ctx;
  303. const uint32_t n_embd = hparams.n_embd;
  304. const uint32_t n_layer = hparams.n_layer;
  305. const int64_t n_mem = n_layer*n_ctx*n_batch;
  306. const int64_t n_elements = n_embd*n_mem;
  307. // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  308. // struct ggml_init_params params;
  309. // params.mem_size = cache.buf.size;
  310. // params.mem_buffer = cache.buf.addr;
  311. // params.no_alloc = false;
  312. if (!cache->ctx) {
  313. struct ggml_init_params params;
  314. params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
  315. params.mem_buffer = NULL;
  316. params.no_alloc = false;
  317. cache->ctx = ggml_init(params);
  318. if (!cache->ctx) {
  319. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  320. return false;
  321. }
  322. }
  323. cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  324. cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  325. return true;
  326. }
  327. struct ggml_tensor * forward(
  328. struct my_llama_model * model,
  329. struct my_llama_kv_cache * cache,
  330. struct ggml_context * ctx0,
  331. struct ggml_cgraph * gf,
  332. struct ggml_tensor * tokens_input,
  333. const int n_tokens,
  334. const int n_past) {
  335. const int N = n_tokens;
  336. struct my_llama_kv_cache& kv_self = *cache;
  337. const auto & hparams = model->hparams;
  338. const int n_ctx = hparams.n_ctx;
  339. const int n_embd = hparams.n_embd;
  340. const int n_layer = hparams.n_layer;
  341. const int n_head = hparams.n_head;
  342. const int n_rot = hparams.n_rot;
  343. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  344. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  345. struct ggml_tensor * kc = kv_self.k;
  346. struct ggml_tensor * vc = kv_self.v;
  347. // inpL shape [n_embd,N,1,1]
  348. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  349. for (int il = 0; il < n_layer; ++il) {
  350. struct ggml_tensor * inpSA = inpL;
  351. struct ggml_tensor * cur;
  352. // lctx.use_buf(ctx0, 0);
  353. // norm
  354. {
  355. // cur shape [n_embd,N,1,1]
  356. cur = ggml_rms_norm(ctx0, inpL);
  357. // cur = attention_norm*cur
  358. cur = ggml_mul(ctx0,
  359. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  360. cur);
  361. }
  362. // self-attention
  363. {
  364. // compute Q and K and RoPE them
  365. // wq shape [n_embd, n_embd, 1, 1]
  366. // wk shape [n_embd, n_embd, 1, 1]
  367. // Qcur shape [n_embd/n_head, n_head, N, 1]
  368. // Kcur shape [n_embd/n_head, n_head, N, 1]
  369. struct ggml_tensor * Qcur = ggml_rope_inplace(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);
  370. struct ggml_tensor * Kcur = ggml_rope_inplace(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);
  371. // store key and value to memory
  372. {
  373. // compute the transposed [N, n_embd] V matrix
  374. // wv shape [n_embd, n_embd, 1, 1]
  375. // Vcur shape [n_embd, N, 1, 1]
  376. 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)));
  377. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  378. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  379. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  380. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  381. /* {
  382. 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));
  383. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  384. ( n_ctx)*ggml_element_size(kv_self.v),
  385. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  386. // important: storing RoPE-ed version of K in the KV cache!
  387. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  388. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  389. } //*/
  390. kc = ggml_set_1d_inplace(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  391. vc = ggml_set_2d_inplace(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  392. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  393. }
  394. // Qcur shape [n_embd/n_head, n_head, N, 1]
  395. // Q shape [n_embd/n_head, N, n_head, 1]
  396. struct ggml_tensor * Q =
  397. ggml_permute(ctx0,
  398. Qcur,
  399. 0, 2, 1, 3);
  400. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  401. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  402. struct ggml_tensor * K =
  403. ggml_permute(ctx0,
  404. ggml_reshape_3d(ctx0,
  405. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  406. n_embd/n_head, n_head, n_past + N),
  407. 0, 2, 1, 3);
  408. // K * Q
  409. // KQ shape [n_past + N, N, n_head, 1]
  410. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  411. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  412. // KQ_scaled shape [n_past + N, N, n_head, 1]
  413. struct ggml_tensor * KQ_scaled =
  414. ggml_scale(ctx0,
  415. KQ,
  416. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  417. // KQ_masked = mask_past(KQ_scaled)
  418. // KQ_masked shape [n_past + N, N, n_head, 1]
  419. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  420. // KQ = soft_max(KQ_masked)
  421. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  422. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  423. // split cached V into n_head heads
  424. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  425. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  426. struct ggml_tensor * V =
  427. ggml_view_3d(ctx0, vc,
  428. n_past + N, n_embd/n_head, n_head,
  429. n_ctx*ggml_element_size(vc),
  430. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  431. il*n_ctx*ggml_element_size(vc)*n_embd);
  432. // KQV shape [n_embd/n_head, N, n_head, 1]
  433. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  434. // KQV_merged = KQV.permute(0, 2, 1, 3)
  435. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  436. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  437. // KQV_merged shape
  438. // cur = KQV_merged.contiguous().view(n_embd, N)
  439. // cur shape [n_embd,N,1,1]
  440. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  441. // cur = ggml_cpy(ctx0,
  442. // KQV_merged,
  443. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  444. // projection (no bias)
  445. // cur shape [n_embd,N,1,1]
  446. cur = ggml_mul_mat(ctx0,
  447. model->layers[il].wo,
  448. cur);
  449. }
  450. // lctx.use_buf(ctx0, 1);
  451. // inpFF shape [n_embd,N,1,1]
  452. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  453. // feed-forward network
  454. {
  455. // norm
  456. {
  457. // cur shape [n_embd,N,1,1]
  458. cur = ggml_rms_norm(ctx0, inpFF);
  459. // cur = ffn_norm*cur
  460. // cur shape [n_embd,N,1,1]
  461. cur = ggml_mul(ctx0,
  462. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  463. cur);
  464. }
  465. // tmp shape [n_ff,N,1,1]
  466. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  467. model->layers[il].w3,
  468. cur);
  469. // cur shape [n_ff,N,1,1]
  470. cur = ggml_mul_mat(ctx0,
  471. model->layers[il].w1,
  472. cur);
  473. // SILU activation
  474. // cur shape [n_ff,N,1,1]
  475. cur = ggml_silu(ctx0, cur);
  476. // cur shape [n_ff,N,1,1]
  477. cur = ggml_mul(ctx0, cur, tmp);
  478. // cur shape [n_embd,N,1,1]
  479. cur = ggml_mul_mat(ctx0,
  480. model->layers[il].w2,
  481. cur);
  482. }
  483. // cur shape [n_embd,N,1,1]
  484. cur = ggml_add(ctx0, cur, inpFF);
  485. // input for next layer
  486. // inpL shape [n_embd,N,1,1]
  487. inpL = cur;
  488. }
  489. // norm
  490. {
  491. // inpL shape [n_embd,N,1,1]
  492. inpL = ggml_rms_norm(ctx0, inpL);
  493. // inpL = norm*inpL
  494. // inpL shape [n_embd,N,1,1]
  495. inpL = ggml_mul(ctx0,
  496. ggml_repeat(ctx0, model->norm, inpL),
  497. inpL);
  498. //embeddings = inpL;
  499. }
  500. // lm_head
  501. // inpL shape [n_vocab,N,1,1]
  502. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  503. // run the computation
  504. ggml_build_forward_expand(gf, inpL);
  505. return inpL;
  506. }
  507. void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
  508. GGML_ASSERT(tensor->n_dims == 1);
  509. GGML_ASSERT(tensor->ne[0] == ne0);
  510. }
  511. void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
  512. GGML_ASSERT(tensor->n_dims == 2);
  513. GGML_ASSERT(tensor->ne[0] == ne0);
  514. GGML_ASSERT(tensor->ne[1] == ne1);
  515. }
  516. void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
  517. GGML_ASSERT(tensor->n_dims == 3);
  518. GGML_ASSERT(tensor->ne[0] == ne0);
  519. GGML_ASSERT(tensor->ne[1] == ne1);
  520. GGML_ASSERT(tensor->ne[2] == ne2);
  521. }
  522. void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  523. GGML_ASSERT(tensor->n_dims == 4);
  524. GGML_ASSERT(tensor->ne[0] == ne0);
  525. GGML_ASSERT(tensor->ne[1] == ne1);
  526. GGML_ASSERT(tensor->ne[2] == ne2);
  527. GGML_ASSERT(tensor->ne[3] == ne3);
  528. }
  529. struct ggml_tensor * forward_batch(
  530. struct my_llama_model * model,
  531. struct my_llama_kv_cache * cache,
  532. struct ggml_context * ctx0,
  533. struct ggml_cgraph * gf,
  534. struct ggml_tensor * tokens_input,
  535. const int n_tokens,
  536. const int n_past,
  537. const int n_batch) {
  538. const int N = n_tokens;
  539. struct my_llama_kv_cache& kv_self = *cache;
  540. const auto & hparams = model->hparams;
  541. const int n_ctx = hparams.n_ctx;
  542. const int n_vocab = hparams.n_vocab;
  543. const int n_embd = hparams.n_embd;
  544. const int n_layer = hparams.n_layer;
  545. const int n_head = hparams.n_head;
  546. const int n_rot = hparams.n_rot;
  547. const int n_ff = get_n_ff(&hparams);
  548. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  549. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  550. struct ggml_tensor * kc = kv_self.k;
  551. struct ggml_tensor * vc = kv_self.v;
  552. // inpL shape [n_embd,N*n_batch,1]
  553. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  554. assert_shape_2d(inpL, n_embd, N*n_batch);
  555. for (int il = 0; il < n_layer; ++il) {
  556. struct ggml_tensor * inpSA = inpL;
  557. struct ggml_tensor * cur;
  558. // lctx.use_buf(ctx0, 0);
  559. // norm
  560. {
  561. // cur shape [n_embd,N*n_batch,1,1]
  562. cur = ggml_rms_norm(ctx0, inpL);
  563. assert_shape_2d(cur, n_embd, N*n_batch);
  564. // cur = attention_norm*cur
  565. cur = ggml_mul(ctx0,
  566. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  567. cur);
  568. assert_shape_2d(cur, n_embd, N*n_batch);
  569. }
  570. // self-attention
  571. {
  572. // compute Q and K and RoPE them
  573. // wq shape [n_embd, n_embd, 1, 1]
  574. // wk shape [n_embd, n_embd, 1, 1]
  575. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  576. // Kcur shape [n_embd/n_head, n_head, N, n_batch]
  577. struct ggml_tensor * Qcur = ggml_rope_inplace(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);
  578. struct ggml_tensor * Kcur = ggml_rope_inplace(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);
  579. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  580. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  581. // store key and value to memory
  582. {
  583. // compute the transposed [N, n_embd] V matrix
  584. // wv shape [n_embd, n_embd, 1, 1]
  585. // Vcur shape [N, n_embd, n_batch, 1]
  586. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  587. ggml_permute(ctx0,
  588. ggml_reshape_3d(ctx0,
  589. ggml_mul_mat(ctx0,
  590. model->layers[il].wv,
  591. cur),
  592. n_embd, N, n_batch),
  593. 1, 0, 2, 3));
  594. assert_shape_3d(Vcur, N, n_embd, n_batch);
  595. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  596. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  597. // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
  598. // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
  599. /* {
  600. 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));
  601. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  602. ( n_ctx)*ggml_element_size(kv_self.v),
  603. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  604. // important: storing RoPE-ed version of K in the KV cache!
  605. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  606. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  607. } //*/
  608. kc = ggml_set_2d_inplace(ctx0, kc,
  609. ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
  610. ggml_element_size(kc)*n_embd*n_ctx,
  611. (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
  612. vc = ggml_set_2d_inplace(ctx0, vc,
  613. ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
  614. ggml_element_size(vc)*n_ctx*n_embd,
  615. ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
  616. assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
  617. assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
  618. }
  619. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  620. // Q shape [n_embd/n_head, N, n_head, n_batch]
  621. struct ggml_tensor * Q =
  622. ggml_permute(ctx0,
  623. Qcur,
  624. 0, 2, 1, 3);
  625. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  626. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  627. // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
  628. struct ggml_tensor * K =
  629. ggml_permute(ctx0,
  630. ggml_reshape_4d(ctx0,
  631. ggml_view_3d(ctx0,
  632. kc,
  633. n_embd,
  634. (n_past + N),
  635. n_batch,
  636. n_embd*ggml_element_size(kc),
  637. n_ctx*n_embd*ggml_element_size(kc),
  638. il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
  639. n_embd/n_head, n_head, n_past + N, n_batch),
  640. 0, 2, 1, 3);
  641. assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
  642. // K * Q
  643. // KQ shape [n_past + N, N, n_head, n_batch]
  644. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  645. assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
  646. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  647. // KQ_scaled shape [n_past + N, N, n_head, n_batch]
  648. struct ggml_tensor * KQ_scaled =
  649. ggml_scale_inplace(ctx0,
  650. KQ,
  651. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  652. assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
  653. // KQ_masked = mask_past(KQ_scaled)
  654. // KQ_masked shape [n_past + N, N, n_head, n_batch]
  655. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  656. assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
  657. // KQ = soft_max(KQ_masked)
  658. // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
  659. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  660. assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
  661. // split cached V into n_head heads
  662. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  663. // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
  664. struct ggml_tensor * V =
  665. ggml_view_4d(ctx0, vc,
  666. n_past + N, n_embd/n_head, n_head, n_batch,
  667. ggml_element_size(vc)*n_ctx,
  668. ggml_element_size(vc)*n_ctx*n_embd/n_head,
  669. ggml_element_size(vc)*n_ctx*n_embd,
  670. il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
  671. assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
  672. // KQV shape [n_embd/n_head, N, n_head, n_batch]
  673. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  674. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  675. // KQV_merged = KQV.permute(0, 2, 1, 3)
  676. // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
  677. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  678. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  679. // KQV_merged shape
  680. // cur = KQV_merged.contiguous().view(n_embd, N)
  681. // cur shape [n_embd,N*n_batch,1,1]
  682. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  683. assert_shape_2d(cur, n_embd, N*n_batch);
  684. // cur = ggml_cpy(ctx0,
  685. // KQV_merged,
  686. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  687. // projection (no bias)
  688. // cur shape [n_embd,N*n_batch,1,1]
  689. cur = ggml_mul_mat(ctx0,
  690. model->layers[il].wo,
  691. cur);
  692. assert_shape_2d(cur, n_embd, N*n_batch);
  693. }
  694. // lctx.use_buf(ctx0, 1);
  695. // inpFF shape [n_embd,N*n_batch,1,1]
  696. struct ggml_tensor * inpFF = ggml_add_inplace(ctx0, cur, inpSA);
  697. assert_shape_2d(inpFF, n_embd, N*n_batch);
  698. // feed-forward network
  699. {
  700. // norm
  701. {
  702. // cur shape [n_embd,N*n_batch,1,1]
  703. cur = ggml_rms_norm(ctx0, inpFF);
  704. assert_shape_2d(cur, n_embd, N*n_batch);
  705. // cur = ffn_norm*cur
  706. // cur shape [n_embd,N*n_batch,1,1]
  707. cur = ggml_mul(ctx0,
  708. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  709. cur);
  710. assert_shape_2d(cur, n_embd, N*n_batch);
  711. }
  712. // tmp shape [n_ff,N*n_batch,1,1]
  713. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  714. model->layers[il].w3,
  715. cur);
  716. assert_shape_2d(tmp, n_ff, N*n_batch);
  717. // cur shape [n_ff,N*n_batch,1,1]
  718. cur = ggml_mul_mat(ctx0,
  719. model->layers[il].w1,
  720. cur);
  721. assert_shape_2d(cur, n_ff, N*n_batch);
  722. // SILU activation
  723. // cur shape [n_ff,N*n_batch,1,1]
  724. cur = ggml_silu(ctx0, cur);
  725. assert_shape_2d(cur, n_ff, N*n_batch);
  726. // cur shape [n_ff,N*n_batch,1,1]
  727. cur = ggml_mul(ctx0, cur, tmp);
  728. assert_shape_2d(cur, n_ff, N*n_batch);
  729. // cur shape [n_embd,N*n_batch,1,1]
  730. cur = ggml_mul_mat(ctx0,
  731. model->layers[il].w2,
  732. cur);
  733. assert_shape_2d(cur, n_embd, N*n_batch);
  734. }
  735. // cur shape [n_embd,N*n_batch,1,1]
  736. cur = ggml_add_inplace(ctx0, cur, inpFF);
  737. assert_shape_2d(cur, n_embd, N*n_batch);
  738. // input for next layer
  739. // inpL shape [n_embd,N*n_batch,1,1]
  740. inpL = cur;
  741. assert_shape_2d(inpL, n_embd, N*n_batch);
  742. }
  743. // norm
  744. {
  745. // inpL shape [n_embd,N*n_batch,1,1]
  746. inpL = ggml_rms_norm(ctx0, inpL);
  747. assert_shape_2d(inpL, n_embd, N*n_batch);
  748. // inpL = norm*inpL
  749. // inpL shape [n_embd,N*n_batch,1,1]
  750. inpL = ggml_mul(ctx0,
  751. ggml_repeat(ctx0, model->norm, inpL),
  752. inpL);
  753. assert_shape_2d(inpL, n_embd, N*n_batch);
  754. //embeddings = inpL;
  755. }
  756. // lm_head
  757. // inpL shape [n_vocab,N*n_batch,1,1]
  758. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  759. assert_shape_2d(inpL, n_vocab, N*n_batch);
  760. {
  761. // inpL shape [n_vocab,N,n_batch,1]
  762. inpL = ggml_reshape_3d(ctx0,
  763. inpL,
  764. n_vocab, N, n_batch);
  765. assert_shape_3d(inpL, n_vocab, N, n_batch);
  766. }
  767. // run the computation
  768. ggml_build_forward_expand(gf, inpL);
  769. return inpL;
  770. }
  771. struct ggml_tensor * forward_batch_wo_cache(
  772. struct my_llama_model * model,
  773. struct ggml_context * ctx0,
  774. struct ggml_cgraph * gf,
  775. struct ggml_tensor * tokens_input,
  776. const int n_tokens,
  777. const int n_batch) {
  778. const int n_past = 0;
  779. const int N = n_tokens;
  780. const auto & hparams = model->hparams;
  781. //const int n_ctx = hparams.n_ctx;
  782. const int n_vocab = hparams.n_vocab;
  783. const int n_embd = hparams.n_embd;
  784. const int n_layer = hparams.n_layer;
  785. const int n_head = hparams.n_head;
  786. const int n_rot = hparams.n_rot;
  787. const int n_ff = get_n_ff(&hparams);
  788. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  789. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  790. // inpL shape [n_embd,N*n_batch,1]
  791. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  792. assert_shape_2d(inpL, n_embd, N*n_batch);
  793. for (int il = 0; il < n_layer; ++il) {
  794. struct ggml_tensor * inpSA = inpL;
  795. struct ggml_tensor * cur;
  796. // lctx.use_buf(ctx0, 0);
  797. // norm
  798. {
  799. // cur shape [n_embd,N*n_batch,1,1]
  800. cur = ggml_rms_norm(ctx0, inpL);
  801. assert_shape_2d(cur, n_embd, N*n_batch);
  802. // cur = attention_norm*cur
  803. cur = ggml_mul(ctx0,
  804. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  805. cur);
  806. assert_shape_2d(cur, n_embd, N*n_batch);
  807. }
  808. // self-attention
  809. {
  810. // compute Q and K and RoPE them
  811. // wq shape [n_embd, n_embd, 1, 1]
  812. // wk shape [n_embd, n_embd, 1, 1]
  813. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  814. // Kcur shape [n_embd/n_head, n_head, N, n_batch]
  815. struct ggml_tensor * Qcur = ggml_rope_inplace(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);
  816. struct ggml_tensor * Kcur = ggml_rope_inplace(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);
  817. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  818. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  819. // Vcur shape [N, n_batch, n_embd/n_head, n_head]
  820. struct ggml_tensor * Vcur = ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, cur, model->layers[il].wv), N, n_batch, n_embd/n_head, n_head);
  821. assert_shape_4d(Vcur, N, n_batch, n_embd/n_head, n_head);
  822. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  823. // Q shape [n_embd/n_head, N, n_head, n_batch]
  824. struct ggml_tensor * Q =
  825. ggml_permute(ctx0,
  826. Qcur,
  827. 0, 2, 1, 3);
  828. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  829. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  830. // K shape [n_embd/n_head, N, n_head, n_batch]
  831. struct ggml_tensor * K =
  832. ggml_permute(ctx0,
  833. Kcur,
  834. 0, 2, 1, 3);
  835. assert_shape_4d(K, n_embd/n_head, N, n_head, n_batch);
  836. // K * Q
  837. // KQ shape [N, N, n_head, n_batch]
  838. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  839. assert_shape_4d(KQ, N, N, n_head, n_batch);
  840. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  841. // KQ_scaled shape [N, N, n_head, n_batch]
  842. struct ggml_tensor * KQ_scaled =
  843. ggml_scale_inplace(ctx0,
  844. KQ,
  845. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  846. assert_shape_4d(KQ_scaled, N, N, n_head, n_batch);
  847. // KQ_masked = mask_past(KQ_scaled)
  848. // KQ_masked shape [N, N, n_head, n_batch]
  849. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  850. assert_shape_4d(KQ_masked, N, N, n_head, n_batch);
  851. // KQ = soft_max(KQ_masked)
  852. // KQ_soft_max shape [N, N, n_head, n_batch]
  853. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  854. assert_shape_4d(KQ_soft_max, N, N, n_head, n_batch);
  855. // Vcur shape [N, n_batch, n_embd/n_head, n_head]
  856. // V shape [N, n_embd/n_head, n_head, n_batch]
  857. struct ggml_tensor * V =
  858. ggml_permute(ctx0,
  859. Vcur,
  860. 0, 3, 1, 2);
  861. assert_shape_4d(V, N, n_embd/n_head, n_head, n_batch);
  862. // KQV shape [n_embd/n_head, N, n_head, n_batch]
  863. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  864. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  865. // KQV_merged = KQV.permute(0, 2, 1, 3)
  866. // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
  867. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  868. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  869. // KQV_merged shape
  870. // cur shape [n_embd,N*n_batch,1,1]
  871. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  872. assert_shape_2d(cur, n_embd, N*n_batch);
  873. // projection (no bias)
  874. // cur shape [n_embd,N*n_batch,1,1]
  875. cur = ggml_mul_mat(ctx0,
  876. model->layers[il].wo,
  877. cur);
  878. assert_shape_2d(cur, n_embd, N*n_batch);
  879. }
  880. // lctx.use_buf(ctx0, 1);
  881. // inpFF shape [n_embd,N*n_batch,1,1]
  882. struct ggml_tensor * inpFF = ggml_add_inplace(ctx0, cur, inpSA);
  883. assert_shape_2d(inpFF, n_embd, N*n_batch);
  884. // feed-forward network
  885. {
  886. // norm
  887. {
  888. // cur shape [n_embd,N*n_batch,1,1]
  889. cur = ggml_rms_norm(ctx0, inpFF);
  890. assert_shape_2d(cur, n_embd, N*n_batch);
  891. // cur = ffn_norm*cur
  892. // cur shape [n_embd,N*n_batch,1,1]
  893. cur = ggml_mul(ctx0,
  894. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  895. cur);
  896. assert_shape_2d(cur, n_embd, N*n_batch);
  897. }
  898. // tmp shape [n_ff,N*n_batch,1,1]
  899. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  900. model->layers[il].w3,
  901. cur);
  902. assert_shape_2d(tmp, n_ff, N*n_batch);
  903. // cur shape [n_ff,N*n_batch,1,1]
  904. cur = ggml_mul_mat(ctx0,
  905. model->layers[il].w1,
  906. cur);
  907. assert_shape_2d(cur, n_ff, N*n_batch);
  908. // SILU activation
  909. // cur shape [n_ff,N*n_batch,1,1]
  910. cur = ggml_silu(ctx0, cur);
  911. assert_shape_2d(cur, n_ff, N*n_batch);
  912. // cur shape [n_ff,N*n_batch,1,1]
  913. cur = ggml_mul(ctx0, cur, tmp);
  914. assert_shape_2d(cur, n_ff, N*n_batch);
  915. // cur shape [n_embd,N*n_batch,1,1]
  916. cur = ggml_mul_mat(ctx0,
  917. model->layers[il].w2,
  918. cur);
  919. assert_shape_2d(cur, n_embd, N*n_batch);
  920. }
  921. // cur shape [n_embd,N*n_batch,1,1]
  922. cur = ggml_add_inplace(ctx0, cur, inpFF);
  923. assert_shape_2d(cur, n_embd, N*n_batch);
  924. // input for next layer
  925. // inpL shape [n_embd,N*n_batch,1,1]
  926. inpL = cur;
  927. assert_shape_2d(inpL, n_embd, N*n_batch);
  928. }
  929. // norm
  930. {
  931. // inpL shape [n_embd,N*n_batch,1,1]
  932. inpL = ggml_rms_norm(ctx0, inpL);
  933. assert_shape_2d(inpL, n_embd, N*n_batch);
  934. // inpL = norm*inpL
  935. // inpL shape [n_embd,N*n_batch,1,1]
  936. inpL = ggml_mul(ctx0,
  937. ggml_repeat(ctx0, model->norm, inpL),
  938. inpL);
  939. assert_shape_2d(inpL, n_embd, N*n_batch);
  940. //embeddings = inpL;
  941. }
  942. // lm_head
  943. // inpL shape [n_vocab,N*n_batch,1,1]
  944. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  945. assert_shape_2d(inpL, n_vocab, N*n_batch);
  946. {
  947. // inpL shape [n_vocab,N,n_batch,1]
  948. inpL = ggml_reshape_3d(ctx0,
  949. inpL,
  950. n_vocab, N, n_batch);
  951. assert_shape_3d(inpL, n_vocab, N, n_batch);
  952. }
  953. // run the computation
  954. ggml_build_forward_expand(gf, inpL);
  955. return inpL;
  956. }
  957. struct ggml_tensor * forward_batch_wo_cache_flash_attn(
  958. struct my_llama_model * model,
  959. struct ggml_context * ctx0,
  960. struct ggml_cgraph * gf,
  961. struct ggml_tensor * tokens_input,
  962. const int n_tokens,
  963. const int n_batch) {
  964. const int n_past = 0;
  965. const int N = n_tokens;
  966. const auto & hparams = model->hparams;
  967. //const int n_ctx = hparams.n_ctx;
  968. const int n_vocab = hparams.n_vocab;
  969. const int n_embd = hparams.n_embd;
  970. const int n_layer = hparams.n_layer;
  971. const int n_head = hparams.n_head;
  972. const int n_rot = hparams.n_rot;
  973. const int n_ff = get_n_ff(&hparams);
  974. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  975. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  976. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  977. assert_shape_2d(inpL, n_embd, N*n_batch);
  978. for (int il = 0; il < n_layer; ++il) {
  979. struct ggml_tensor * inpSA = inpL;
  980. struct ggml_tensor * cur;
  981. // norm
  982. {
  983. cur = ggml_rms_norm(ctx0, inpL);
  984. assert_shape_2d(cur, n_embd, N*n_batch);
  985. // cur = attention_norm*cur
  986. cur = ggml_mul(ctx0,
  987. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  988. cur);
  989. assert_shape_2d(cur, n_embd, N*n_batch);
  990. }
  991. // self-attention
  992. {
  993. // compute Q and K and RoPE them
  994. // wq shape [n_embd, n_embd, 1, 1]
  995. // wk shape [n_embd, n_embd, 1, 1]
  996. struct ggml_tensor * Qcur = ggml_rope_inplace(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);
  997. struct ggml_tensor * Kcur = ggml_rope_inplace(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);
  998. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  999. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  1000. struct ggml_tensor * Vcur = ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, cur, model->layers[il].wv), N, n_batch, n_embd/n_head, n_head);
  1001. assert_shape_4d(Vcur, N, n_batch, n_embd/n_head, n_head);
  1002. struct ggml_tensor * Q =
  1003. ggml_permute(ctx0,
  1004. Qcur,
  1005. 0, 2, 1, 3);
  1006. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  1007. struct ggml_tensor * K =
  1008. ggml_permute(ctx0,
  1009. Kcur,
  1010. 0, 2, 1, 3);
  1011. assert_shape_4d(K, n_embd/n_head, N, n_head, n_batch);
  1012. struct ggml_tensor * V =
  1013. ggml_permute(ctx0,
  1014. Vcur,
  1015. 0, 3, 1, 2);
  1016. assert_shape_4d(V, N, n_embd/n_head, n_head, n_batch);
  1017. bool masked = true;
  1018. struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, masked);
  1019. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  1020. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1021. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  1022. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  1023. assert_shape_2d(cur, n_embd, N*n_batch);
  1024. // projection (no bias)
  1025. cur = ggml_mul_mat(ctx0,
  1026. model->layers[il].wo,
  1027. cur);
  1028. assert_shape_2d(cur, n_embd, N*n_batch);
  1029. }
  1030. struct ggml_tensor * inpFF = ggml_add_inplace(ctx0, cur, inpSA);
  1031. assert_shape_2d(inpFF, n_embd, N*n_batch);
  1032. // feed-forward network
  1033. {
  1034. // norm
  1035. {
  1036. cur = ggml_rms_norm(ctx0, inpFF);
  1037. assert_shape_2d(cur, n_embd, N*n_batch);
  1038. // cur = ffn_norm*cur
  1039. cur = ggml_mul(ctx0,
  1040. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  1041. cur);
  1042. assert_shape_2d(cur, n_embd, N*n_batch);
  1043. }
  1044. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1045. model->layers[il].w3,
  1046. cur);
  1047. assert_shape_2d(tmp, n_ff, N*n_batch);
  1048. cur = ggml_mul_mat(ctx0,
  1049. model->layers[il].w1,
  1050. cur);
  1051. assert_shape_2d(cur, n_ff, N*n_batch);
  1052. // SILU activation
  1053. cur = ggml_silu(ctx0, cur);
  1054. assert_shape_2d(cur, n_ff, N*n_batch);
  1055. cur = ggml_mul(ctx0, cur, tmp);
  1056. assert_shape_2d(cur, n_ff, N*n_batch);
  1057. cur = ggml_mul_mat(ctx0,
  1058. model->layers[il].w2,
  1059. cur);
  1060. assert_shape_2d(cur, n_embd, N*n_batch);
  1061. }
  1062. cur = ggml_add_inplace(ctx0, cur, inpFF);
  1063. assert_shape_2d(cur, n_embd, N*n_batch);
  1064. // input for next layer
  1065. inpL = cur;
  1066. assert_shape_2d(inpL, n_embd, N*n_batch);
  1067. }
  1068. // norm
  1069. {
  1070. inpL = ggml_rms_norm(ctx0, inpL);
  1071. assert_shape_2d(inpL, n_embd, N*n_batch);
  1072. // inpL = norm*inpL
  1073. inpL = ggml_mul(ctx0,
  1074. ggml_repeat(ctx0, model->norm, inpL),
  1075. inpL);
  1076. assert_shape_2d(inpL, n_embd, N*n_batch);
  1077. }
  1078. // lm_head
  1079. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  1080. assert_shape_2d(inpL, n_vocab, N*n_batch);
  1081. {
  1082. inpL = ggml_reshape_3d(ctx0,
  1083. inpL,
  1084. n_vocab, N, n_batch);
  1085. assert_shape_3d(inpL, n_vocab, N, n_batch);
  1086. }
  1087. // run the computation
  1088. ggml_build_forward_expand(gf, inpL);
  1089. return inpL;
  1090. }
  1091. // expand the graph nodes without creating leafs.
  1092. struct ggml_tensor * expand(struct ggml_cgraph * g, struct ggml_tensor * t) {
  1093. // check if already visited
  1094. for (int i = 0; i < g->n_nodes; i++) {
  1095. if (g->nodes[i] == t) {
  1096. return t;
  1097. }
  1098. }
  1099. for (int i = 0; i < g->n_leafs; i++) {
  1100. if (g->leafs[i] == t) {
  1101. return t;
  1102. }
  1103. }
  1104. if (t->src0) {
  1105. expand(g, t->src0);
  1106. }
  1107. if (t->src1) {
  1108. expand(g, t->src1);
  1109. }
  1110. for (int i = 0; i < GGML_MAX_OPT; ++i) {
  1111. if (t->opt[i]) {
  1112. expand(g, t->opt[i]);
  1113. }
  1114. }
  1115. GGML_ASSERT(g->n_nodes < GGML_MAX_NODES);
  1116. if (strlen(t->name) == 0) {
  1117. snprintf(t->name, sizeof(t->name), "node_%d", g->n_nodes);
  1118. }
  1119. g->nodes[g->n_nodes] = t;
  1120. g->grads[g->n_nodes] = t->grad;
  1121. g->n_nodes++;
  1122. return t;
  1123. }
  1124. void graph_set_leafs_grads(struct ggml_cgraph * g) {
  1125. // moves leaf nodes to g->leafs.
  1126. // i.e. g->n_nodes might change.
  1127. int n_nodes = 0;
  1128. for (int i = 0; i < g->n_nodes; ++i) {
  1129. struct ggml_tensor * node = g->nodes[i];
  1130. const bool is_leaf = node->op == GGML_OP_NONE && node->grad == NULL;
  1131. if (is_leaf) {
  1132. GGML_ASSERT(g->n_leafs < GGML_MAX_NODES);
  1133. if (strlen(node->name) == 0) {
  1134. snprintf(node->name, sizeof(node->name), "leaf_%d", g->n_leafs);
  1135. }
  1136. g->leafs[g->n_leafs] = node;
  1137. g->n_leafs++;
  1138. } else {
  1139. GGML_ASSERT(n_nodes < GGML_MAX_NODES);
  1140. if (strlen(node->name) == 0) {
  1141. snprintf(node->name, sizeof(node->name), "node_%d", n_nodes);
  1142. }
  1143. g->nodes[n_nodes] = node;
  1144. g->grads[n_nodes] = node->grad;
  1145. n_nodes++;
  1146. }
  1147. }
  1148. for (int i=n_nodes; i < g->n_nodes; ++i) {
  1149. g->nodes[n_nodes] = NULL;
  1150. g->grads[n_nodes] = NULL;
  1151. }
  1152. g->n_nodes = n_nodes;
  1153. }
  1154. struct ggml_tensor * forward_batch_wo_cache_flash_attn_train(
  1155. struct my_llama_model * model,
  1156. struct ggml_context * ctx0,
  1157. struct ggml_cgraph * gf,
  1158. struct ggml_cgraph * gb,
  1159. struct ggml_tensor * * logits,
  1160. struct ggml_tensor * tokens_input,
  1161. struct ggml_tensor * targets,
  1162. void * compute_buf_0,
  1163. void * compute_buf_1,
  1164. size_t size_buf_0,
  1165. size_t size_buf_1,
  1166. const int n_tokens,
  1167. const int n_batch) {
  1168. ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  1169. const int n_past = 0;
  1170. const int N = n_tokens;
  1171. gf->n_nodes = 0;
  1172. gf->n_leafs = 0;
  1173. gf->work_size = 0;
  1174. gf->perf_runs = 0;
  1175. gf->perf_cycles = 0;
  1176. gf->perf_time_us = 0;
  1177. gf->work = NULL;
  1178. const auto & hparams = model->hparams;
  1179. //const int n_ctx = hparams.n_ctx;
  1180. const int n_vocab = hparams.n_vocab;
  1181. const int n_embd = hparams.n_embd;
  1182. const int n_layer = hparams.n_layer;
  1183. const int n_head = hparams.n_head;
  1184. const int n_rot = hparams.n_rot;
  1185. const int n_ff = get_n_ff(&hparams);
  1186. const int rope_mode = 0;
  1187. int last_buf = -1;
  1188. size_t buf_offs[2] = { 0, 0 };
  1189. size_t buf_size[2] = { size_buf_0,
  1190. size_buf_1 };
  1191. void * buf_data[2] = { compute_buf_0,
  1192. compute_buf_1 };
  1193. auto use_buf = [ctx0, &last_buf, &buf_offs, &buf_size, &buf_data] (int buf) {
  1194. size_t last_offs = 0;
  1195. last_offs = ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  1196. if (last_buf >= 0) {
  1197. buf_offs[last_buf] = last_offs;
  1198. }
  1199. if (buf >= 0) {
  1200. size_t offs = buf_offs[buf];
  1201. size_t size = buf_size[buf];
  1202. void * data = buf_data[buf];
  1203. ggml_set_scratch(ctx0, { offs, size, data, });
  1204. }
  1205. last_buf = buf;
  1206. };
  1207. bool track_max_mem = false;
  1208. size_t buf_maxs[2] = { 0, 0 };
  1209. auto clr_buf = [ctx0, &last_buf, &buf_offs, &buf_size, &buf_data, &buf_maxs, track_max_mem] (int buf) {
  1210. if (buf < 0) return;
  1211. if (track_max_mem) {
  1212. size_t last_offs = 0;
  1213. last_offs = ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  1214. if (last_buf >= 0) {
  1215. buf_offs[last_buf] = last_offs;
  1216. buf_maxs[last_buf] = std::max(buf_maxs[last_buf], buf_offs[last_buf]);
  1217. }
  1218. }
  1219. buf_offs[buf] = 0;
  1220. if (track_max_mem && last_buf >= 0) {
  1221. size_t offs = buf_offs[last_buf];
  1222. size_t size = buf_size[last_buf];
  1223. void * data = buf_data[last_buf];
  1224. ggml_set_scratch(ctx0, { offs, size, data, });
  1225. }
  1226. };
  1227. auto view__q = [ctx0, n_embd, n_head, N, n_batch] (struct ggml_tensor * t) -> struct ggml_tensor * {
  1228. int64_t ne0 = n_embd/n_head;
  1229. int64_t ne1 = N;
  1230. int64_t ne2 = n_head;
  1231. int64_t ne3 = n_batch;
  1232. size_t nb0 = ggml_element_size(t);
  1233. size_t nb1 = nb0*ne0;
  1234. size_t nb2 = nb1*ne1;
  1235. size_t nb3 = nb2*ne2;
  1236. size_t offset = 0;
  1237. return ggml_view_4d(ctx0, t, ne0, ne1, ne2, ne3, nb1, nb2, nb3, offset);
  1238. };
  1239. auto view__k = [ctx0, n_embd, n_head, N, n_batch] (struct ggml_tensor * t) -> struct ggml_tensor * {
  1240. int64_t ne0 = n_embd/n_head;
  1241. int64_t ne1 = N;
  1242. int64_t ne2 = n_head;
  1243. int64_t ne3 = n_batch;
  1244. size_t nb0 = ggml_element_size(t);
  1245. size_t nb1 = nb0*ne0;
  1246. size_t nb2 = nb1*ne1;
  1247. size_t nb3 = nb2*ne2;
  1248. size_t offset = nb3*ne3;
  1249. return ggml_view_4d(ctx0, t, ne0, ne1, ne2, ne3, nb1, nb2, nb3, offset);
  1250. };
  1251. auto view__v = [ctx0, n_embd, n_head, N, n_batch] (struct ggml_tensor * t) -> struct ggml_tensor * {
  1252. int64_t ne0 = N;
  1253. int64_t ne1 = n_embd/n_head;
  1254. int64_t ne2 = n_head;
  1255. int64_t ne3 = n_batch;
  1256. size_t nb0 = ggml_element_size(t);
  1257. size_t nb1 = nb0*ne0;
  1258. size_t nb2 = nb1*ne1;
  1259. size_t nb3 = nb2*ne2;
  1260. size_t offset = 2*nb3*ne3;
  1261. return ggml_view_4d(ctx0, t, ne0, ne1, ne2, ne3, nb1, nb2, nb3, offset);
  1262. };
  1263. auto add_or_set = [ctx0] (struct ggml_tensor * a, struct ggml_tensor * b) -> struct ggml_tensor * {
  1264. if (a == NULL) {
  1265. return b;
  1266. } else {
  1267. return ggml_add_inplace(ctx0, a, b);
  1268. }
  1269. };
  1270. use_buf(-1);
  1271. model->tok_embeddings->grad = NULL;
  1272. model->norm->grad = NULL;
  1273. model->output->grad = NULL;
  1274. for (int il = 0; il < n_layer; ++il) {
  1275. struct my_llama_layer & layer = model->layers[il];
  1276. layer.attention_norm->grad = NULL;
  1277. layer.wq->grad = NULL;
  1278. layer.wk->grad = NULL;
  1279. layer.wv->grad = NULL;
  1280. layer.wo->grad = NULL;
  1281. layer.ffn_norm->grad = NULL;
  1282. layer.w1->grad = NULL;
  1283. layer.w2->grad = NULL;
  1284. layer.w3->grad = NULL;
  1285. }
  1286. clr_buf(0);
  1287. clr_buf(1);
  1288. use_buf(-1);
  1289. struct ggml_tensor * t00 = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch); assert_shape_1d(t00, N*n_batch);
  1290. memcpy(t00->data, tokens_input->data, ggml_element_size(t00)*N*n_batch);
  1291. use_buf(-1);
  1292. struct ggml_tensor * t01 = expand(gf, ggml_get_rows(ctx0, model->tok_embeddings, t00)); assert_shape_2d(t01, n_embd, N*n_batch);
  1293. // need to remember these for the backward pass
  1294. std::vector<struct ggml_tensor *> t02L; t02L.resize(n_layer, NULL);
  1295. std::vector<struct ggml_tensor *> t03L; t03L.resize(n_layer, NULL);
  1296. std::vector<struct ggml_tensor *> t04L; t04L.resize(n_layer, NULL);
  1297. std::vector<struct ggml_tensor *> t05L; t05L.resize(n_layer, NULL);
  1298. std::vector<struct ggml_tensor *> t06L; t06L.resize(n_layer, NULL);
  1299. std::vector<struct ggml_tensor *> t07L; t07L.resize(n_layer, NULL);
  1300. std::vector<struct ggml_tensor *> t08L; t08L.resize(n_layer, NULL);
  1301. std::vector<struct ggml_tensor *> t09L; t09L.resize(n_layer, NULL);
  1302. std::vector<struct ggml_tensor *> t10L; t10L.resize(n_layer, NULL);
  1303. std::vector<struct ggml_tensor *> t11L; t11L.resize(n_layer, NULL);
  1304. std::vector<struct ggml_tensor *> t12L; t12L.resize(n_layer, NULL);
  1305. std::vector<struct ggml_tensor *> t13L; t13L.resize(n_layer, NULL);
  1306. std::vector<struct ggml_tensor *> t14L; t14L.resize(n_layer, NULL);
  1307. std::vector<struct ggml_tensor *> t15L; t15L.resize(n_layer, NULL);
  1308. std::vector<struct ggml_tensor *> t16L; t16L.resize(n_layer, NULL);
  1309. std::vector<struct ggml_tensor *> t17L; t17L.resize(n_layer, NULL);
  1310. std::vector<struct ggml_tensor *> t18L; t18L.resize(n_layer, NULL);
  1311. std::vector<struct ggml_tensor *> t19L; t19L.resize(n_layer, NULL);
  1312. std::vector<struct ggml_tensor *> t20L; t20L.resize(n_layer, NULL);
  1313. std::vector<struct ggml_tensor *> t21L; t21L.resize(n_layer, NULL);
  1314. std::vector<struct ggml_tensor *> t22L; t22L.resize(n_layer, NULL);
  1315. std::vector<struct ggml_tensor *> t23L; t23L.resize(n_layer, NULL);
  1316. std::vector<struct ggml_tensor *> t24L; t24L.resize(n_layer, NULL);
  1317. std::vector<struct ggml_tensor *> t25L; t25L.resize(n_layer, NULL);
  1318. std::vector<struct ggml_tensor *> t26L; t26L.resize(n_layer, NULL);
  1319. std::vector<struct ggml_tensor *> t27L; t27L.resize(n_layer, NULL);
  1320. std::vector<struct ggml_tensor *> t28L; t28L.resize(n_layer, NULL);
  1321. std::vector<struct ggml_tensor *> t29L; t29L.resize(n_layer, NULL);
  1322. std::vector<struct ggml_tensor *> t30L; t30L.resize(n_layer, NULL);
  1323. struct ggml_tensor * cur = t01;
  1324. for (int il = 0; il < n_layer; ++il) {
  1325. clr_buf(0);
  1326. struct my_llama_layer & layer = model->layers[il];
  1327. // tensors with values necessary for backward pass are in persistent buf(-1)
  1328. // other tensors with buf(0) and buf(1) are only temporary needed, and their memory reused after layer is completed.
  1329. use_buf(-1); struct ggml_tensor * t02 = expand(gf, ggml_rms_norm (ctx0, cur)); assert_shape_2d(t02, n_embd, N*n_batch);
  1330. use_buf( 0); struct ggml_tensor * t03 = expand(gf, ggml_repeat (ctx0, layer.attention_norm, t02)); assert_shape_2d(t03, n_embd, N*n_batch);
  1331. use_buf(-1); struct ggml_tensor * t04 = expand(gf, ggml_mul (ctx0, t02, t03)); assert_shape_2d(t04, n_embd, N*n_batch);
  1332. use_buf(-1); struct ggml_tensor * t05 = expand(gf, ggml_mul_mat (ctx0, layer.wq, t04)); assert_shape_2d(t05, n_embd, N*n_batch);
  1333. use_buf(-1); struct ggml_tensor * t06 = expand(gf, ggml_reshape_4d (ctx0, t05, n_embd/n_head, n_head, N, n_batch)); assert_shape_4d(t06, n_embd/n_head, n_head, N, n_batch);
  1334. use_buf(-1); struct ggml_tensor * t07 = expand(gf, ggml_rope_inplace (ctx0, t06, n_past, n_rot, rope_mode)); assert_shape_4d(t07, n_embd/n_head, n_head, N, n_batch);
  1335. use_buf(-1); struct ggml_tensor * t08 = expand(gf, ggml_mul_mat (ctx0, layer.wk, t04)); assert_shape_2d(t08, n_embd, N*n_batch);
  1336. use_buf(-1); struct ggml_tensor * t09 = expand(gf, ggml_reshape_4d (ctx0, t08, n_embd/n_head, n_head, N, n_batch)); assert_shape_4d(t09, n_embd/n_head, n_head, N, n_batch);
  1337. use_buf(-1); struct ggml_tensor * t10 = expand(gf, ggml_rope_inplace (ctx0, t09, n_past, n_rot, rope_mode)); assert_shape_4d(t10, n_embd/n_head, n_head, N, n_batch);
  1338. use_buf(-1); struct ggml_tensor * t11 = expand(gf, ggml_mul_mat (ctx0, t04, layer.wv)); assert_shape_2d(t11, N*n_batch, n_embd);
  1339. use_buf(-1); struct ggml_tensor * t12 = expand(gf, ggml_reshape_4d (ctx0, t11, N, n_batch, n_embd/n_head, n_head)); assert_shape_4d(t12, N, n_batch, n_embd/n_head, n_head);
  1340. use_buf(-1); struct ggml_tensor * t13 = expand(gf, ggml_permute (ctx0, t07, 0, 2, 1, 3)); assert_shape_4d(t13, n_embd/n_head, N, n_head, n_batch);
  1341. use_buf(-1); struct ggml_tensor * t14 = expand(gf, ggml_permute (ctx0, t10, 0, 2, 1, 3)); assert_shape_4d(t14, n_embd/n_head, N, n_head, n_batch);
  1342. use_buf(-1); struct ggml_tensor * t15 = expand(gf, ggml_permute (ctx0, t12, 0, 3, 1, 2)); assert_shape_4d(t15, N, n_embd/n_head, n_head, n_batch);
  1343. use_buf(-1); struct ggml_tensor * t16 = expand(gf, ggml_flash_attn (ctx0, t13, t14, t15, true)); assert_shape_4d(t16, n_embd/n_head, N, n_head, n_batch);
  1344. use_buf( 0); struct ggml_tensor * t17 = expand(gf, ggml_permute (ctx0, t16, 0, 2, 1, 3)); assert_shape_4d(t17, n_embd/n_head, n_head, N, n_batch);
  1345. use_buf(-1); struct ggml_tensor * t18 = expand(gf, ggml_cont (ctx0, t17)); assert_shape_4d(t18, n_embd/n_head, n_head, N, n_batch);
  1346. use_buf(-1); struct ggml_tensor * t19 = expand(gf, ggml_reshape_2d (ctx0, t18, n_embd, N*n_batch)); assert_shape_2d(t19, n_embd, N*n_batch);
  1347. use_buf( 0); struct ggml_tensor * t20 = expand(gf, ggml_mul_mat (ctx0, layer.wo, t19)); assert_shape_2d(t20, n_embd, N*n_batch);
  1348. use_buf(-1); struct ggml_tensor * t21 = expand(gf, ggml_add (ctx0, t20, cur)); assert_shape_2d(t21, n_embd, N*n_batch);
  1349. use_buf(-1); struct ggml_tensor * t22 = expand(gf, ggml_rms_norm (ctx0, t21)); assert_shape_2d(t22, n_embd, N*n_batch);
  1350. use_buf( 0); struct ggml_tensor * t23 = expand(gf, ggml_repeat (ctx0, layer.ffn_norm, t22)); assert_shape_2d(t23, n_embd, N*n_batch);
  1351. use_buf(-1); struct ggml_tensor * t24 = expand(gf, ggml_mul (ctx0, t23, t22)); assert_shape_2d(t24, n_embd, N*n_batch);
  1352. use_buf(-1); struct ggml_tensor * t25 = expand(gf, ggml_mul_mat (ctx0, layer.w3, t24)); assert_shape_2d(t25, n_ff, N*n_batch);
  1353. use_buf(-1); struct ggml_tensor * t26 = expand(gf, ggml_mul_mat (ctx0, layer.w1, t24)); assert_shape_2d(t26, n_ff, N*n_batch);
  1354. use_buf(-1); struct ggml_tensor * t27 = expand(gf, ggml_silu (ctx0, t26)); assert_shape_2d(t27, n_ff, N*n_batch);
  1355. use_buf(-1); struct ggml_tensor * t28 = expand(gf, ggml_mul (ctx0, t27, t25)); assert_shape_2d(t28, n_ff, N*n_batch);
  1356. use_buf( 0); struct ggml_tensor * t29 = expand(gf, ggml_mul_mat (ctx0, layer.w2, t28)); assert_shape_2d(t29, n_embd, N*n_batch);
  1357. use_buf(-1); struct ggml_tensor * t30 = expand(gf, ggml_add (ctx0, t21, t29)); assert_shape_2d(t30, n_embd, N*n_batch);
  1358. t02L[il] = t02;
  1359. t03L[il] = t03;
  1360. t04L[il] = t04;
  1361. t05L[il] = t05;
  1362. t06L[il] = t06;
  1363. t07L[il] = t07;
  1364. t08L[il] = t08;
  1365. t09L[il] = t09;
  1366. t10L[il] = t10;
  1367. t11L[il] = t11;
  1368. t12L[il] = t12;
  1369. t13L[il] = t13;
  1370. t14L[il] = t14;
  1371. t15L[il] = t15;
  1372. t16L[il] = t16;
  1373. t17L[il] = t17;
  1374. t18L[il] = t18;
  1375. t19L[il] = t19;
  1376. t20L[il] = t20;
  1377. t21L[il] = t21;
  1378. t22L[il] = t22;
  1379. t23L[il] = t23;
  1380. t24L[il] = t24;
  1381. t25L[il] = t25;
  1382. t26L[il] = t26;
  1383. t27L[il] = t27;
  1384. t28L[il] = t28;
  1385. t29L[il] = t29;
  1386. t30L[il] = t30;
  1387. cur = t30;
  1388. }
  1389. clr_buf(0);
  1390. use_buf(0);
  1391. struct ggml_tensor * t31 = expand(gf, ggml_rms_norm (ctx0, cur)); assert_shape_2d(t31, n_embd, N*n_batch);
  1392. struct ggml_tensor * t32 = expand(gf, ggml_repeat (ctx0, model->norm, t31)); assert_shape_2d(t32, n_embd, N*n_batch);
  1393. struct ggml_tensor * t33 = expand(gf, ggml_mul (ctx0, t32, t31)); assert_shape_2d(t33, n_embd, N*n_batch);
  1394. use_buf(-1);
  1395. struct ggml_tensor * t34 = expand(gf, ggml_mul_mat (ctx0, model->output, t33)); assert_shape_2d(t34, n_vocab, N*n_batch);
  1396. struct ggml_tensor * t35 = expand(gf, ggml_reshape_3d(ctx0, t34, n_vocab, N, n_batch)); assert_shape_3d(t35, n_vocab, N, n_batch);
  1397. struct ggml_tensor * t36 = expand(gf, ggml_cross_entropy_loss(ctx0, t35, targets)); assert_shape_1d(t36, 1);
  1398. {
  1399. /*
  1400. tok_embeddings | grad_tok_embeddings = ggml_get_rows_back(grad_t01, t00)
  1401. L0_att_norm | grad_L0_att_norm = ggml_repeat_back(grad_t03L0, L0_att_norm.shape)
  1402. L0_wq | grad_L0_wq = ggml_out_prod(t04L0, grad_t05L0)
  1403. L0_wk | grad_L0_wk = ggml_out_prod(t04L0, grad_t08L0)
  1404. L0_wv | grad_L0_wv = ggml_out_prod(t04L0, ggml_transpose(grad_t11L0))
  1405. L0_wo | grad_L0_wo = ggml_out_prod(t19L0, grad_t20L0)
  1406. L0_ffn_norm | grad_L0_ffn_norm = ggml_repeat_back(grad_t23L0, L0_ffn_norm.shape)
  1407. L0_w1 | grad_L0_w1 = ggml_out_prod(t24L0, grad_t26L0)
  1408. L0_w2 | grad_L0_w2 = ggml_out_prod(t28L0, grad_t29L0)
  1409. L0_w3 | grad_L0_w3 = ggml_out_prod(t24L0, grad_t25L0)
  1410. L1_att_norm | grad_L1_att_norm = ggml_repeat_back(grad_t03L1, L1_att_norm.shape)
  1411. L1_wq | grad_L1_wq = ggml_out_prod(t04L1, grad_t05L1)
  1412. L1_wk | grad_L1_wk = ggml_out_prod(t04L1, grad_t08L1)
  1413. L1_wv | grad_L1_wv = ggml_out_prod(t04L1, ggml_transpose(grad_t11L1))
  1414. L1_wo | grad_L1_wo = ggml_out_prod(t19L1, grad_t20L1)
  1415. L1_ffn_norm | grad_L1_ffn_norm = ggml_repeat_back(grad_t23L1, L1_ffn_norm.shape)
  1416. L1_w1 | grad_L1_w1 = ggml_out_prod(t24L1, grad_t26L1)
  1417. L1_w2 | grad_L1_w2 = ggml_out_prod(t28L1, grad_t29L1)
  1418. L1_w3 | grad_L1_w3 = ggml_out_prod(t24L1, grad_t25L1)
  1419. norm | grad_norm = ggml_repeat_back(grad_t32, norm.shape)
  1420. output | grad_output = ggml_out_prod(t33, grad_t34)
  1421. |
  1422. t01 = ggml_get_rows(tok_embeddings, t00) | grad_t01 = grad_t21L0 + ggml_rms_norm_back(t01, grad_t02L0)
  1423. for layer: |
  1424. t02L0*= ggml_rms_norm (t01) | grad_t02L0 = ggml_mul(grad_t04L0, t03L0)
  1425. t03L0 = ggml_repeat (L0_att_norm, t02L0_shape) | grad_t03L0 = ggml_mul(grad_t04L0, t02L0)
  1426. t04L0*= ggml_mul (t02L0, t03L0) | grad_t04L0 = ggml_out_prod(L0_wv, grad_t11L0) + ggml_out_prod(L0_wk, ggml_transpose(grad_t08L0)) + ggml_out_prod(L0_wq, ggml_transpose(grad_t05L0))
  1427. t05L0 = ggml_mul_mat (L0_wq, t04L0) | grad_t05L0 = ggml_reshape(grad_t06L0, t05L0_shape)
  1428. t06L0 = ggml_reshape_4d (t05L0, n_embd/n_head, n_head, N, n_batch) | grad_t06L0 = ggml_rope_back(grad_t07L0)
  1429. t07L0 = ggml_rope_inplace (t06L0) | grad_t07L0 = ggml_permute_back(grad_t13L0, 0, 2, 1, 3) = ggml_permute(grad_t13L0, 0, 2, 1, 3)
  1430. t08L0 = ggml_mul_mat (L0_wk, t04L0) | grad_t08L0 = ggml_reshape(grad_t09L0, t08L0_shape)
  1431. t09L0 = ggml_reshape_4d (t08L0, n_embd/n_head, n_head, N, n_batch) | grad_t09L0 = ggml_rope_back(grad_t10L0)
  1432. t10L0 = ggml_rope_inplace (t09L0) | grad_t10L0 = ggml_permute_back(grad_t14L0, 0, 2, 1, 3) = ggml_permute(grad_t14L0, 0, 2, 1, 3)
  1433. t11L0 = ggml_mul_mat (t04L0, L0_wv) | grad_t11L0 = ggml_reshape(grad_t12L0, t11L0_shape)
  1434. t12L0 = ggml_reshape_4d (t11L0, N, n_batch, n_embd/n_head, n_head) | grad_t12L0 = ggml_permute_back(grad_t15L0, 0, 3, 1, 2) = ggml_permute(grad_t15L0, 0, 2, 3, 1)
  1435. t13L0*= ggml_permute (t07L0, 0, 2, 1, 3) | grad_t13L0 = view__q(ggml_flash_attn_back(t13L0, t14L0, t15L0, grad_t16L0))
  1436. t14L0*= ggml_permute (t10L0, 0, 2, 1, 3) | grad_t14L0 = view__k(ggml_flash_attn_back(t13L0, t14L0, t15L0, grad_t16L0))
  1437. t15L0*= ggml_permute (t12L0, 0, 3, 1, 2) | grad_t15L0 = view__v(ggml_flash_attn_back(t13L0, t14L0, t15L0, grad_t16L0))
  1438. t16L0 = ggml_flash_attn (t13L0, t14L0, t15L0) | grad_t16L0 = ggml_permute_back(grad_t17L0, 0, 2, 1, 3) = ggml_permute(grad_t17L0, 0, 2, 1, 3)
  1439. t17L0 = ggml_permute (t16L0, 0, 2, 1, 3) | grad_t17L0 = grad_t18L0
  1440. t18L0 = ggml_cont (t17L0) | grad_t18L0 = ggml_reshape(grad_t19L0, t18L0_shape)
  1441. t19L0*= ggml_reshape_2d (t18L0, n_embd, N*n_batch) | grad_t19L0 = ggml_out_prod(L0_wo, ggml_transpose(grad_t20L0))
  1442. t20L0 = ggml_mul_mat (L0_wo, t19L0) | grad_t20L0 = grad_t21L0
  1443. t21L0*= ggml_add (t20L0, t01) | grad_t21L0 = grad_t30L0 + ggml_rms_norm_back(t21L0, grad_t22L0)
  1444. t22L0*= ggml_rms_norm (t21L0) | grad_t22L0 = ggml_mul(grad_t24L0, t23L0)
  1445. t23L0 = ggml_repeat (L0_ffn_norm, t22L0_shape) | grad_t23L0 = ggml_mul(grad_t24L0, t22L0)
  1446. t24L0*= ggml_mul (t23L0, t22L0) | grad_t24L0 = ggml_out_prod(L0_w1, ggml_transpose(grad_t26L0)) + ggml_out_prod(L0_w3, ggml_transpose(grad_t25L0))
  1447. t25L0*= ggml_mul_mat (L0_w3, t24L0) | grad_t25L0 = ggml_mul(grad_t28L0, t27L0)
  1448. t26L0*= ggml_mul_mat (L0_w1, t24L0) | grad_t26L0 = ggml_silu_back(t26L0, grad_t27L0)
  1449. t27L0*= ggml_silu (t26L0) | grad_t27L0 = ggml_mul(grad_t28L0, t25L0)
  1450. t28L0*= ggml_mul (t27L0, t25L0) | grad_t28L0 = ggml_out_prod(L0_w2, ggml_transpose(grad_t29L0))
  1451. t29L0 = ggml_mul_mat (L0_w2, t28L0) | grad_t29L0 = grad_t30L0
  1452. t30L0*= ggml_add (t21L0, t29L0) | grad_t30L0 = ggml_rms_norm_back(t30L0, grad_t02L1) + grad_t21L1
  1453. ^
  1454. t02L1*= ggml_rms_norm (t30L0) | grad_t02L1 = ggml_mul(grad_t04L1, t03L1)
  1455. t03L1 = ggml_repeat (L1_att_norm, t02L1_shape) | grad_t03L1 = ggml_mul(grad_t04L1, t02L1)
  1456. t04L1*= ggml_mul (t02L1, t03L1) | grad_t04L1 = ggml_out_prod(L1_wv, grad_t11L1) + ggml_out_prod(L1_wk, ggml_transpose(grad_t08L1)) + ggml_out_prod(L1_wq, ggml_transpose(grad_t05L1))
  1457. t05L1 = ggml_mul_mat (L1_wq, t04L1) | grad_t05L1 = ggml_reshape(grad_t06L1, t05L1_shape)
  1458. t06L1 = ggml_reshape_4d (t05L1, n_embd/n_head, n_head, N, n_batch) | grad_t06L1 = ggml_rope_back(grad_t07L1)
  1459. t07L1 = ggml_rope_inplace (t06L1) | grad_t07L1 = ggml_permute_back(grad_t13L1, 0, 2, 1, 3) = ggml_permute(grad_t13L1, 0, 2, 1, 3)
  1460. t08L1 = ggml_mul_mat (L1_wk, t04L1) | grad_t08L1 = ggml_reshape(grad_t09L1, t08L1_shape)
  1461. t09L1 = ggml_reshape_4d (t08L1, n_embd/n_head, n_head, N, n_batch) | grad_t09L1 = ggml_rope_back(grad_t10L1)
  1462. t10L1 = ggml_rope_inplace (t09L1) | grad_t10L1 = ggml_permute_back(grad_t14L1, 0, 2, 1, 3) = ggml_permute(grad_t14L1, 0, 2, 1, 3)
  1463. t11L1 = ggml_mul_mat (t04L1, L1_wv) | grad_t11L1 = ggml_reshape(grad_t12L1, t11L1_shape)
  1464. t12L1 = ggml_reshape_4d (t11L1, N, n_batch, n_embd/n_head, n_head) | grad_t12L1 = ggml_permute_back(grad_t15L1, 0, 3, 1, 2) = ggml_permute(grad_t15L1, 0, 2, 3, 1)
  1465. t13L1*= ggml_permute (t07L1, 0, 2, 1, 3) | grad_t13L1 = view__q(ggml_flash_attn_back(t13L1, t14L1, t15L1, grad_t16L1))
  1466. t14L1*= ggml_permute (t10L1, 0, 2, 1, 3) | grad_t14L1 = view__k(ggml_flash_attn_back(t13L1, t14L1, t15L1, grad_t16L1))
  1467. t15L1*= ggml_permute (t12L1, 0, 3, 1, 2) | grad_t15L1 = view__v(ggml_flash_attn_back(t13L1, t14L1, t15L1, grad_t16L1))
  1468. t16L1 = ggml_flash_attn (t13L1, t14L1, t15L1) | grad_t16L1 = ggml_permute_back(grad_t17L1, 0, 2, 1, 3) = ggml_permute(grad_t17L1, 0, 2, 1, 3)
  1469. t17L1 = ggml_permute (t16L1, 0, 2, 1, 3) | grad_t17L1 = grad_t18L1
  1470. t18L1 = ggml_cont (t17L1) | grad_t18L1 = ggml_reshape(grad_t19L1, t18L1_shape)
  1471. t19L1*= ggml_reshape_2d (t18L1, n_embd, N*n_batch) | grad_t19L1 = ggml_out_prod(L1_wo, ggml_transpose(grad_t20L1))
  1472. t20L1 = ggml_mul_mat (L1_wo, t19L1) | grad_t20L1 = grad_t21L1
  1473. t21L1*= ggml_add (t20L1, t30L0) | grad_t21L1 = grad_t30L1 + ggml_rms_norm_back(t21L1, grad_t22L1)
  1474. t22L1*= ggml_rms_norm (t21L1) | grad_t22L1 = ggml_mul(grad_t24L1, t23L1)
  1475. t23L1 = ggml_repeat (L1_ffn_norm, t22L1_shape) | grad_t23L1 = ggml_mul(grad_t24L1, t22L1)
  1476. t24L1*= ggml_mul (t23L1, t22L1) | grad_t24L1 = ggml_out_prod(L1_w1, ggml_transpose(grad_t26L1)) + ggml_out_prod(L1_w3, ggml_transpose(grad_t25L1))
  1477. t25L1*= ggml_mul_mat (L1_w3, t24L1) | grad_t25L1 = ggml_mul(grad_t28L1, t27L1)
  1478. t26L1*= ggml_mul_mat (L1_w1, t24L1) | grad_t26L1 = ggml_silu_back(t26L1, grad_t27L1)
  1479. t27L1*= ggml_silu (t26L1) | grad_t27L1 = ggml_mul(grad_t28L1, t25L1)
  1480. t28L1*= ggml_mul (t27L1, t25L1) | grad_t28L1 = ggml_out_prod(L1_w2, ggml_transpose(grad_t29L1))
  1481. t29L1 = ggml_mul_mat (L1_w2, t28L1) | grad_t29L1 = grad_t30L1
  1482. t30L1*= ggml_add (t21L1, t29L1) | grad_t30L1 = ggml_rms_norm_back(t30L1, grad_t31)
  1483. ^
  1484. t31 = ggml_rms_norm (t30L1) | grad_t31 = ggml_mul(grad_t33, t32)
  1485. t32 = ggml_repeat (norm, t31.shape) | grad_t32 = ggml_mul(grad_t33, t31)
  1486. t33 = ggml_mul (t32, t31) | grad_t33 = ggml_out_prod(output, ggml_transpose(grad_t34))
  1487. t34 = ggml_mul_mat (output, t33) | grad_t34 = ggml_reshape(grad_t35, t34.shape)
  1488. t35 = ggml_reshape_3d (t34, n_vocab, N, n_batch) | grad_t35 = ggml_cross_entropy_loss_back(t35, targets, grad_t36)
  1489. t36 = ggml_cross_entropy_loss(t35, targets) | grad_t36 = 1 (optimizer)
  1490. tensors marked with * need to be stored until grad computation
  1491. tensors during grad computation are all temporary
  1492. */
  1493. }
  1494. *gb = *gf;
  1495. // t36->grad gets set to one by optimizer, so we need the tensor.
  1496. // initialize it with 1.0f to make sure.
  1497. use_buf(-1);
  1498. t36->grad = expand(gb, ggml_new_f32(ctx0, 1.0f));
  1499. use_buf(0);
  1500. t35->grad = expand(gb, ggml_cross_entropy_loss_back(ctx0, t35, targets, t36->grad)); assert_shape_3d(t35->grad, n_vocab, N, n_batch);
  1501. t34->grad = expand(gb, ggml_reshape_2d (ctx0, t35->grad, n_vocab, N*n_batch)); assert_shape_2d(t34->grad, n_vocab, N*n_batch);
  1502. t33->grad = expand(gb, ggml_out_prod (ctx0, model->output, ggml_transpose(ctx0, t34->grad))); assert_shape_2d(t33->grad, n_embd, N*n_batch);
  1503. t32->grad = expand(gb, ggml_mul (ctx0, t33->grad, t31)); assert_shape_2d(t32->grad, n_embd, N*n_batch);
  1504. use_buf(-1);
  1505. model->norm->grad = expand(gb, add_or_set(model->norm->grad, ggml_repeat_back(ctx0, t32->grad, model->norm))); assert_shape_1d(model->norm->grad, n_embd);
  1506. model->output->grad = expand(gb, add_or_set(model->output->grad, ggml_out_prod(ctx0, t33, t34->grad))); assert_shape_2d(model->output->grad, n_embd, n_vocab);
  1507. clr_buf(1);
  1508. use_buf(1);
  1509. t31->grad = expand(gb, ggml_mul(ctx0, t33->grad, t32)); assert_shape_2d(t31->grad, n_embd, N*n_batch);
  1510. struct ggml_tensor * back_layer_inp = t31;
  1511. struct ggml_tensor * grad_layer_inp = NULL;
  1512. for (int k = 0; k < n_layer; ++k) {
  1513. int il = n_layer-1-k;
  1514. struct my_llama_layer & layer = model->layers[il];
  1515. struct ggml_tensor * t02 = t02L[il];
  1516. struct ggml_tensor * t03 = t03L[il];
  1517. struct ggml_tensor * t04 = t04L[il];
  1518. struct ggml_tensor * t05 = t05L[il];
  1519. struct ggml_tensor * t06 = t06L[il];
  1520. struct ggml_tensor * t07 = t07L[il];
  1521. struct ggml_tensor * t08 = t08L[il];
  1522. struct ggml_tensor * t09 = t09L[il];
  1523. struct ggml_tensor * t10 = t10L[il];
  1524. struct ggml_tensor * t11 = t11L[il];
  1525. struct ggml_tensor * t12 = t12L[il];
  1526. struct ggml_tensor * t13 = t13L[il];
  1527. struct ggml_tensor * t14 = t14L[il];
  1528. struct ggml_tensor * t15 = t15L[il];
  1529. struct ggml_tensor * t16 = t16L[il];
  1530. struct ggml_tensor * t17 = t17L[il];
  1531. struct ggml_tensor * t18 = t18L[il];
  1532. struct ggml_tensor * t19 = t19L[il];
  1533. struct ggml_tensor * t20 = t20L[il];
  1534. struct ggml_tensor * t21 = t21L[il];
  1535. struct ggml_tensor * t22 = t22L[il];
  1536. struct ggml_tensor * t23 = t23L[il];
  1537. struct ggml_tensor * t24 = t24L[il];
  1538. struct ggml_tensor * t25 = t25L[il];
  1539. struct ggml_tensor * t26 = t26L[il];
  1540. struct ggml_tensor * t27 = t27L[il];
  1541. struct ggml_tensor * t28 = t28L[il];
  1542. struct ggml_tensor * t29 = t29L[il];
  1543. struct ggml_tensor * t30 = t30L[il];
  1544. clr_buf(0);
  1545. use_buf(0);
  1546. t30->grad = expand(gb, ggml_rms_norm_back(ctx0, t30, back_layer_inp->grad)); assert_shape_2d(t30->grad, n_embd, N*n_batch);
  1547. if (grad_layer_inp) {
  1548. t30->grad = expand(gb, ggml_add(ctx0, t30->grad, grad_layer_inp->grad)); assert_shape_2d(t30->grad, n_embd, N*n_batch);
  1549. }
  1550. clr_buf(1);
  1551. t29->grad = t30->grad; assert_shape_2d(t29->grad, n_embd, N*n_batch);
  1552. t28->grad = expand(gb, ggml_out_prod(ctx0, layer.w2, ggml_transpose(ctx0, t29->grad))); assert_shape_2d(t28->grad, n_ff, N*n_batch);
  1553. t27->grad = expand(gb, ggml_mul(ctx0, t28->grad, t25)); assert_shape_2d(t27->grad, n_ff, N*n_batch);
  1554. t26->grad = expand(gb, ggml_silu_back(ctx0, t26, t27->grad)); assert_shape_2d(t26->grad, n_ff, N*n_batch);
  1555. t25->grad = expand(gb, ggml_mul(ctx0, t28->grad, t27)); assert_shape_2d(t25->grad, n_ff, N*n_batch);
  1556. t24->grad = expand(gb, ggml_add_inplace(ctx0,
  1557. ggml_out_prod(ctx0, layer.w1, ggml_transpose(ctx0, t26->grad)),
  1558. ggml_out_prod(ctx0, layer.w3, ggml_transpose(ctx0, t25->grad)))); assert_shape_2d(t24->grad, n_embd, N*n_batch);
  1559. t23->grad = expand(gb, ggml_mul(ctx0, t24->grad, t22)); assert_shape_2d(t23->grad, n_embd, N*n_batch);
  1560. t22->grad = expand(gb, ggml_mul(ctx0, t24->grad, ggml_repeat(ctx0, layer.ffn_norm, t24->grad))); assert_shape_2d(t22->grad, n_embd, N*n_batch);
  1561. use_buf(1);
  1562. t21->grad = expand(gb, ggml_add(ctx0, t30->grad, ggml_rms_norm_back(ctx0, t21, t22->grad))); assert_shape_2d(t21->grad, n_embd, N*n_batch);
  1563. grad_layer_inp = t21;
  1564. use_buf(0);
  1565. t20->grad = t21->grad; assert_shape_2d(t20->grad, n_embd, N*n_batch);
  1566. t19->grad = expand(gb, ggml_out_prod(ctx0, layer.wo, ggml_transpose(ctx0, t20->grad))); assert_shape_2d(t19->grad, n_embd, N*n_batch);
  1567. t18->grad = expand(gb, ggml_reshape_4d(ctx0, t19->grad, n_embd/n_head, n_head, N, n_batch)); assert_shape_4d(t18->grad, n_embd/n_head, n_head, N, n_batch);
  1568. t17->grad = t18->grad; assert_shape_4d(t17->grad, n_embd/n_head, n_head, N, n_batch);
  1569. t16->grad = expand(gb, ggml_permute(ctx0, t17->grad, 0, 2, 1, 3)); assert_shape_4d(t16->grad, n_embd/n_head, N, n_head, n_batch);
  1570. struct ggml_tensor * flash_attn = expand(gb, ggml_flash_attn_back(ctx0, t13, t14, t15, t16->grad, true)); assert_shape_4d(flash_attn, n_embd/n_head, N*3, n_head, n_batch);
  1571. t15->grad = expand(gb, view__v(flash_attn)); assert_shape_4d(t15->grad, N, n_embd/n_head, n_head, n_batch);
  1572. t14->grad = expand(gb, view__k(flash_attn)); assert_shape_4d(t14->grad, n_embd/n_head, N, n_head, n_batch);
  1573. t13->grad = expand(gb, view__q(flash_attn)); assert_shape_4d(t13->grad, n_embd/n_head, N, n_head, n_batch);
  1574. t12->grad = expand(gb, ggml_permute(ctx0, t15->grad, 0, 2, 3, 1)); assert_shape_4d(t12->grad, N, n_batch, n_embd/n_head, n_head);
  1575. t11->grad = expand(gb, ggml_reshape_2d(ctx0, ggml_cont(ctx0, t12->grad), N*n_batch, n_embd)); assert_shape_2d(t11->grad, N*n_batch, n_embd);
  1576. t10->grad = expand(gb, ggml_permute(ctx0, t14->grad, 0, 2, 1, 3)); assert_shape_4d(t10->grad, n_embd/n_head, n_head, N, n_batch);
  1577. t09->grad = expand(gb, ggml_rope_back(ctx0, t10->grad, n_past, n_rot, rope_mode)); assert_shape_4d(t09->grad, n_embd/n_head, n_head, N, n_batch);
  1578. t08->grad = expand(gb, ggml_reshape_2d(ctx0, t09->grad, n_embd, N*n_batch)); assert_shape_2d(t08->grad, n_embd, N*n_batch);
  1579. t07->grad = expand(gb, ggml_permute(ctx0, t13->grad, 0, 2, 1, 3)); assert_shape_4d(t07->grad, n_embd/n_head, n_head, N, n_batch);
  1580. t06->grad = expand(gb, ggml_rope_back(ctx0, t07->grad, n_past, n_rot, rope_mode)); assert_shape_4d(t06->grad, n_embd/n_head, n_head, N, n_batch);
  1581. t05->grad = expand(gb, ggml_reshape_2d(ctx0, t06->grad, n_embd, N*n_batch)); assert_shape_2d(t05->grad, n_embd, N*n_batch);
  1582. t04->grad = expand(gb, ggml_add_inplace(ctx0,
  1583. ggml_add_inplace(ctx0,
  1584. ggml_out_prod(ctx0, layer.wv, t11->grad),
  1585. ggml_out_prod(ctx0, layer.wk, ggml_transpose(ctx0, t08->grad))),
  1586. ggml_out_prod(ctx0, layer.wq, ggml_transpose(ctx0, t05->grad)))); assert_shape_2d(t04->grad, n_embd, N*n_batch);
  1587. t03->grad = expand(gb, ggml_mul(ctx0, t04->grad, t02)); assert_shape_2d(t04->grad, n_embd, N*n_batch);
  1588. use_buf(1);
  1589. t02->grad = expand(gb, ggml_mul(ctx0, t04->grad, ggml_repeat(ctx0, layer.attention_norm, t02))); assert_shape_2d(t02->grad, n_embd, N*n_batch);
  1590. back_layer_inp = t02;
  1591. // use_buf(0);
  1592. use_buf(-1);
  1593. layer.attention_norm->grad = expand(gb, add_or_set(layer.attention_norm->grad, ggml_repeat_back(ctx0, t03->grad, layer.attention_norm))); assert_shape_1d(layer.attention_norm->grad, n_embd);
  1594. layer.wq->grad = expand(gb, add_or_set(layer.wq->grad, ggml_out_prod(ctx0, t04, t05->grad))); assert_shape_2d(layer.wq->grad, n_embd, n_embd);
  1595. layer.wk->grad = expand(gb, add_or_set(layer.wk->grad, ggml_out_prod(ctx0, t04, t08->grad))); assert_shape_2d(layer.wk->grad, n_embd, n_embd);
  1596. layer.wv->grad = expand(gb, add_or_set(layer.wv->grad, ggml_out_prod(ctx0, t04, ggml_transpose(ctx0, t11->grad)))); assert_shape_2d(layer.wv->grad, n_embd, n_embd);
  1597. layer.wo->grad = expand(gb, add_or_set(layer.wo->grad, ggml_out_prod(ctx0, t19, t20->grad))); assert_shape_2d(layer.wo->grad, n_embd, n_embd);
  1598. layer.ffn_norm->grad = expand(gb, add_or_set(layer.ffn_norm->grad, ggml_repeat_back(ctx0, t23->grad, layer.ffn_norm))); assert_shape_1d(layer.ffn_norm->grad, n_embd);
  1599. layer.w1->grad = expand(gb, add_or_set(layer.w1->grad, ggml_out_prod(ctx0, t24, t26->grad))); assert_shape_2d(layer.w1->grad, n_embd, n_ff);
  1600. layer.w2->grad = expand(gb, add_or_set(layer.w2->grad, ggml_out_prod(ctx0, t28, t29->grad))); assert_shape_2d(layer.w2->grad, n_ff, n_embd);
  1601. layer.w3->grad = expand(gb, add_or_set(layer.w3->grad, ggml_out_prod(ctx0, t24, t25->grad))); assert_shape_2d(layer.w3->grad, n_embd, n_ff);
  1602. // use_buf(0);
  1603. }
  1604. clr_buf(0);
  1605. use_buf(0);
  1606. t01->grad = expand(gb, ggml_add_inplace(ctx0, grad_layer_inp->grad, ggml_rms_norm_back(ctx0, t01, back_layer_inp->grad))); assert_shape_2d(t01->grad, n_embd, N*n_batch);
  1607. use_buf(-1);
  1608. model->tok_embeddings->grad = expand(gb, ggml_get_rows_back(ctx0, t01->grad, t00, model->tok_embeddings)); assert_shape_2d(model->tok_embeddings->grad, n_embd, n_vocab);
  1609. // clr_buf(1);
  1610. // clr_buf(0);
  1611. *logits = t35;
  1612. if (track_max_mem) {
  1613. printf("%s: max size compute buf0: %zu\n", __func__, buf_maxs[0]);
  1614. printf("%s: max size compute buf1: %zu\n", __func__, buf_maxs[1]);
  1615. }
  1616. // now that all grads are created, set the graph leafs and grads
  1617. graph_set_leafs_grads(gf);
  1618. graph_set_leafs_grads(gb);
  1619. return t36;
  1620. }
  1621. void set_f32_3d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int64_t i2, float value) {
  1622. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  1623. *ptr = value;
  1624. }
  1625. void set_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, float value) {
  1626. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  1627. *ptr = value;
  1628. }
  1629. void set_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int32_t value) {
  1630. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  1631. *ptr = value;
  1632. }
  1633. float get_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  1634. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  1635. return *ptr;
  1636. }
  1637. int32_t get_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  1638. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  1639. return *ptr;
  1640. }
  1641. void print_row(struct ggml_tensor * probs, int i) {
  1642. for (int k = 0; k < probs->ne[0]; ++k) {
  1643. float p = get_f32_2d(probs, k, i);
  1644. printf(" %.2f", p);
  1645. }
  1646. printf("\n");
  1647. }
  1648. void print_matrix(struct ggml_tensor * probs) {
  1649. assert(probs->n_dims == 2);
  1650. for (int i = 0; i < probs->ne[1]; ++i) {
  1651. for (int k = 0; k < probs->ne[0]; ++k) {
  1652. float p = get_f32_2d(probs, k, i);
  1653. printf(" %.2f", p);
  1654. }
  1655. printf("\n");
  1656. }
  1657. }
  1658. void print_token(struct llama_context * ctx, llama_token token) {
  1659. printf("%s", llama_token_to_str(ctx, token));
  1660. }
  1661. void print_tokens(struct llama_context* ctx, struct ggml_tensor * tokens) {
  1662. for (int i=0; i<tokens->ne[0]; ++i) {
  1663. int token = ggml_get_i32_1d(tokens, i);
  1664. print_token(ctx, token);
  1665. }
  1666. }
  1667. void print_tokens_batch(struct llama_context* ctx, struct ggml_tensor * tokens) {
  1668. for (int i1=0; i1<tokens->ne[1]; ++i1) {
  1669. //int num_newline = 0;
  1670. for (int i0=0; i0<tokens->ne[0]; ++i0) {
  1671. int token = get_i32_2d(tokens, i0, i1);
  1672. print_token(ctx, token);
  1673. // bool isnl = (token == llama_token_nl());
  1674. // if (isnl) {
  1675. // ++num_newline;
  1676. // }
  1677. // if (isnl) {
  1678. // if (num_newline < 2) {
  1679. // print_token(ctx, token);
  1680. // } else {
  1681. // printf("\\n");
  1682. // }
  1683. // } else {
  1684. // print_token(ctx, token);
  1685. // }
  1686. }
  1687. printf("\n--\n");
  1688. }
  1689. }
  1690. void get_example_targets(const int * train_samples, size_t n_train_samples, const llama_token * train_data, size_t n_train_data, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * target_logits, struct ggml_tensor * target_probs) {
  1691. int n_tokens = tokens_input->ne[0];
  1692. int n_vocab = target_logits->ne[0];
  1693. size_t sample = train_samples[example_id % n_train_samples];
  1694. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  1695. ggml_set_f32(target_logits, -1.0f/n_vocab);
  1696. ggml_set_f32(target_probs, 0.0f);
  1697. ggml_set_i32_1d(tokens_input, 0, llama_token_bos());
  1698. for (int i=1; i<n_tokens+1; ++i) {
  1699. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  1700. set_f32_2d(target_logits, token, i-1, +1.0f);
  1701. set_f32_2d(target_probs, token, i-1, +1.0f);
  1702. if (i<n_tokens) {
  1703. ggml_set_i32_1d(tokens_input, i, token);
  1704. }
  1705. }
  1706. }
  1707. void get_example_targets_batch(struct llama_context * /*lctx*/, const int * train_samples, size_t n_train_samples, const llama_token * train_data, size_t n_train_data, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * target_logits, struct ggml_tensor * target_probs) {
  1708. GGML_ASSERT(tokens_input->n_dims == 2);
  1709. GGML_ASSERT(target_logits->n_dims == 3);
  1710. GGML_ASSERT(target_probs->n_dims == 3);
  1711. int n_vocab = target_logits->ne[0];
  1712. int n_tokens = tokens_input->ne[0];
  1713. int n_batch = tokens_input->ne[1];
  1714. GGML_ASSERT(n_tokens == target_logits->ne[1]);
  1715. GGML_ASSERT(n_batch == target_logits->ne[2]);
  1716. GGML_ASSERT(n_vocab == target_probs->ne[0]);
  1717. GGML_ASSERT(n_tokens == target_probs->ne[1]);
  1718. GGML_ASSERT(n_batch == target_probs->ne[2]);
  1719. ggml_set_f32(target_logits, -1.0f/n_vocab);
  1720. ggml_set_f32(target_probs, 0.0f);
  1721. for (int k=0; k<n_batch; ++k) {
  1722. // printf("%s: batch %d\n", __func__, k);
  1723. size_t sample = train_samples[(example_id*n_batch + k) % n_train_samples];
  1724. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  1725. set_i32_2d(tokens_input, 0, k, llama_token_bos());
  1726. for (int i=1; i<n_tokens+1; ++i) {
  1727. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  1728. // print_token(lctx, token);
  1729. set_f32_3d(target_logits, token, i-1, k, +1.0f);
  1730. set_f32_3d(target_probs, token, i-1, k, +1.0f);
  1731. if (i<n_tokens) {
  1732. set_i32_2d(tokens_input, i, k, token);
  1733. }
  1734. }
  1735. // printf("\n=\n");
  1736. // for (int i=0; i<n_tokens; ++i) {
  1737. // int token = get_i32_2d(tokens_input, i, k);
  1738. // print_token(lctx, token);
  1739. // }
  1740. // printf("\n-\n");
  1741. }
  1742. }
  1743. void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * target_logits, struct ggml_tensor * target_probs, int n_shift) {
  1744. int n_tokens = tokens_input->ne[0];
  1745. int n_vocab = target_logits->ne[0];
  1746. for (int i=0; i<n_tokens-n_shift; ++i) {
  1747. ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
  1748. for (int k=0; k<n_vocab; ++k) {
  1749. ggml_set_f32_1d(target_logits, i*n_vocab + k, ggml_get_f32_1d(target_logits, (i + n_shift)*n_vocab + k));
  1750. ggml_set_f32_1d(target_probs, i*n_vocab + k, ggml_get_f32_1d(target_probs, (i + n_shift)*n_vocab + k));
  1751. }
  1752. }
  1753. }
  1754. struct ggml_tensor * square_error_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * target) {
  1755. return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, target, a)));
  1756. }
  1757. struct ggml_tensor * cross_entropy_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * probs) {
  1758. return ggml_cross_entropy_loss(ctx, a, probs);
  1759. }
  1760. #ifdef __GNUC__
  1761. #ifdef __MINGW32__
  1762. __attribute__((format(gnu_printf, 1, 2)))
  1763. #else
  1764. __attribute__((format(printf, 1, 2)))
  1765. #endif
  1766. #endif
  1767. static std::string format(const char * fmt, ...) {
  1768. va_list ap, ap2;
  1769. va_start(ap, fmt);
  1770. va_copy(ap2, ap);
  1771. int size = vsnprintf(NULL, 0, fmt, ap);
  1772. GGML_ASSERT(size >= 0 && size < INT_MAX);
  1773. std::vector<char> buf(size + 1);
  1774. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  1775. GGML_ASSERT(size2 == size);
  1776. va_end(ap2);
  1777. va_end(ap);
  1778. return std::string(buf.data(), size);
  1779. }
  1780. struct llama_file {
  1781. // use FILE * so we don't have to re-open the file to mmap
  1782. FILE * fp;
  1783. size_t size;
  1784. llama_file(const char * fname, const char * mode) {
  1785. fp = std::fopen(fname, mode);
  1786. if (fp == NULL) {
  1787. size = 0;
  1788. } else {
  1789. seek(0, SEEK_END);
  1790. size = tell();
  1791. seek(0, SEEK_SET);
  1792. }
  1793. }
  1794. size_t tell() const {
  1795. #ifdef _WIN32
  1796. __int64 ret = _ftelli64(fp);
  1797. #else
  1798. long ret = std::ftell(fp);
  1799. #endif
  1800. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1801. return (size_t) ret;
  1802. }
  1803. void seek(size_t offset, int whence) {
  1804. #ifdef _WIN32
  1805. int ret = _fseeki64(fp, (__int64) offset, whence);
  1806. #else
  1807. int ret = std::fseek(fp, (long) offset, whence);
  1808. #endif
  1809. GGML_ASSERT(ret == 0); // same
  1810. }
  1811. void read_raw(void * ptr, size_t size) {
  1812. if (size == 0) {
  1813. return;
  1814. }
  1815. errno = 0;
  1816. std::size_t ret = std::fread(ptr, size, 1, fp);
  1817. if (ferror(fp)) {
  1818. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1819. }
  1820. if (ret != 1) {
  1821. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  1822. }
  1823. }
  1824. std::uint32_t read_u32() {
  1825. std::uint32_t ret;
  1826. read_raw(&ret, sizeof(ret));
  1827. return ret;
  1828. }
  1829. std::string read_string(std::uint32_t len) {
  1830. std::vector<char> chars(len);
  1831. read_raw(chars.data(), len);
  1832. return std::string(chars.data(), len);
  1833. }
  1834. void write_raw(const void * ptr, size_t size) {
  1835. if (size == 0) {
  1836. return;
  1837. }
  1838. errno = 0;
  1839. size_t ret = std::fwrite(ptr, size, 1, fp);
  1840. if (ret != 1) {
  1841. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1842. }
  1843. }
  1844. void write_u32(std::uint32_t val) {
  1845. write_raw(&val, sizeof(val));
  1846. }
  1847. ~llama_file() {
  1848. if (fp) {
  1849. std::fclose(fp);
  1850. }
  1851. }
  1852. };
  1853. int tokenize_file(struct llama_context * lctx, const char * filename, std::vector<llama_token>& out) {
  1854. struct llama_file f(filename, "rb");
  1855. std::vector<char> buf;
  1856. buf.resize(f.size+1);
  1857. f.read_raw(buf.data(), f.size);
  1858. buf[f.size] = '\0';
  1859. out.resize(buf.size());
  1860. int n_tokens = llama_tokenize(lctx, buf.data(), out.data(), buf.size(), false);
  1861. if (n_tokens >= 0) {
  1862. out.resize(n_tokens);
  1863. }
  1864. bool verify = false;
  1865. if (verify) {
  1866. const char * in = buf.data();
  1867. const char * end = buf.data() + buf.size();
  1868. for (int i = 0; i < (int) out.size(); ++i) {
  1869. const char * s = llama_token_to_str(lctx, out[i]);
  1870. int len = strlen(s);
  1871. if (in >= end) {
  1872. printf("%s: unexpected end of original text.\n", __func__);
  1873. break;
  1874. }
  1875. const bool matches = (strncmp(in, s, len) == 0);
  1876. if (matches) {
  1877. in += len;
  1878. } else {
  1879. printf("%s: mismatch: expected '%s', but got '%s'\n", __func__, std::string(in, len).c_str(), s);
  1880. }
  1881. }
  1882. }
  1883. return n_tokens;
  1884. }
  1885. void shuffle_ints(int * begin, int * end) {
  1886. if (end <= begin) return;
  1887. int max=begin[0];
  1888. for (int i=1; i<end-begin; ++i) {
  1889. if (begin[i] > max) {
  1890. max = begin[i];
  1891. }
  1892. }
  1893. std::vector<float> vals;
  1894. vals.resize(max+1);
  1895. for (int i=0; i<max+1; ++i) {
  1896. vals[i] = frand();
  1897. }
  1898. std::sort(begin, end, [&vals](int a, int b){
  1899. return vals.at(a) < vals.at(b);
  1900. });
  1901. }
  1902. struct my_llama_sampler_params {
  1903. float temp = 0.0f; // <= 0.0 disabled
  1904. int top_k = 20; // <= 0 to use vocab size
  1905. float top_p = 0.95f; // 1.0 = disabled
  1906. float tfs_z = 1.00f; // 1.0 = disabled
  1907. float typical_p = 1.00f; // 1.0 = disabled
  1908. int repeat_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
  1909. float repeat_penalty = 1.0f; // 1.0 = disabled
  1910. float alpha_presence = 0.0f; // 0.0 = disabled
  1911. float alpha_frequency = 0.0f; // 0.0 = disabled
  1912. int mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
  1913. float mirostat_tau = 5.00f; // target entropy
  1914. float mirostat_eta = 0.10f; // learning rate
  1915. bool penalize_nl = true; // consider newlines as a repeatable token
  1916. };
  1917. struct my_llama_sampler {
  1918. struct llama_context * ctx = NULL;
  1919. my_llama_sampler_params params;
  1920. int n_vocab = 0;
  1921. int n_ctx = 0;
  1922. float mirostat_mu;
  1923. std::vector<llama_token_data> candidates;
  1924. llama_token_data_array candidates_p;
  1925. };
  1926. void init_sampler(struct my_llama_sampler * sampler, struct llama_context * ctx) {
  1927. sampler->ctx = ctx;
  1928. sampler->n_vocab = llama_n_vocab(sampler->ctx);
  1929. sampler->n_ctx = llama_n_ctx(sampler->ctx);
  1930. sampler->mirostat_mu = 2.0f * sampler->params.mirostat_tau;
  1931. }
  1932. llama_token sample(struct my_llama_sampler * sampler, float * logits, const llama_token * last_tokens, int n_last_tokens) {
  1933. GGML_ASSERT(sampler->ctx != NULL);
  1934. struct llama_context * ctx = sampler->ctx;
  1935. sampler->candidates.resize(sampler->n_vocab);
  1936. for (llama_token token_id = 0; token_id < sampler->n_vocab; ++token_id) {
  1937. sampler->candidates[token_id].id = token_id;
  1938. sampler->candidates[token_id].logit = logits[token_id];
  1939. sampler->candidates[token_id].p = 0.0;
  1940. }
  1941. llama_token_data_array * candidates_p = & sampler->candidates_p;
  1942. candidates_p->data = sampler->candidates.data();
  1943. candidates_p->size = sampler->candidates.size();
  1944. candidates_p->sorted = false;
  1945. const auto params = sampler->params;
  1946. // Apply penalties
  1947. const float nl_logit = logits[llama_token_nl()];
  1948. const int n_last = std::min(std::min(n_last_tokens, params.repeat_last_n), sampler->n_ctx);
  1949. llama_sample_repetition_penalty(
  1950. ctx,
  1951. candidates_p,
  1952. last_tokens + n_last_tokens - n_last,
  1953. n_last,
  1954. params.repeat_penalty);
  1955. llama_sample_frequency_and_presence_penalties(
  1956. ctx,
  1957. candidates_p,
  1958. last_tokens + n_last_tokens - n_last,
  1959. n_last,
  1960. params.alpha_frequency,
  1961. params.alpha_presence);
  1962. if (!params.penalize_nl) {
  1963. logits[llama_token_nl()] = nl_logit;
  1964. }
  1965. llama_token token = 0;
  1966. if (params.temp <= 0) {
  1967. // Greedy sampling
  1968. token = llama_sample_token_greedy(ctx, candidates_p);
  1969. } else {
  1970. if (params.mirostat == 1) {
  1971. int mirostat_m = 100;
  1972. llama_sample_temperature(ctx, candidates_p, params.temp);
  1973. token = llama_sample_token_mirostat(ctx, candidates_p, params.mirostat_tau, params.mirostat_eta, mirostat_m, &sampler->mirostat_mu);
  1974. } else if (params.mirostat == 2) {
  1975. llama_sample_temperature(ctx, candidates_p, params.temp);
  1976. token = llama_sample_token_mirostat_v2(ctx, candidates_p, params.mirostat_tau, params.mirostat_eta, &sampler->mirostat_mu);
  1977. } else {
  1978. // Temperature sampling
  1979. llama_sample_top_k (ctx, candidates_p, params.top_k, 1);
  1980. llama_sample_tail_free (ctx, candidates_p, params.tfs_z, 1);
  1981. llama_sample_typical (ctx, candidates_p, params.typical_p, 1);
  1982. llama_sample_top_p (ctx, candidates_p, params.top_p, 1);
  1983. llama_sample_temperature (ctx, candidates_p, params.temp);
  1984. token = llama_sample_token(ctx, candidates_p);
  1985. }
  1986. }
  1987. return token;
  1988. }
  1989. void set_logits_masked(struct ggml_tensor * logits, std::vector<bool>& mask, float value) {
  1990. GGML_ASSERT(logits->ne[0] == (int64_t) mask.size());
  1991. for (int i2 = 0; i2 < logits->ne[2]; ++i2) {
  1992. for (int i1 = 0; i1 < logits->ne[1]; ++i1) {
  1993. for (int i0 = 0; i0 < logits->ne[0]; ++i0) {
  1994. if (!mask[i0]) continue;
  1995. float * ptr = (float *) ((char *) logits->data + i2*logits->nb[2] + i1*logits->nb[1] + i0*logits->nb[0]);
  1996. *ptr = value;
  1997. }
  1998. }
  1999. }
  2000. }
  2001. void write_tensor(struct llama_file * file, struct ggml_tensor * tensor) {
  2002. if (tensor == NULL) {
  2003. file->write_u32(0);
  2004. file->write_u32(0);
  2005. file->write_u32(GGML_TYPE_F32);
  2006. file->seek(-file->tell() & 31, SEEK_CUR);
  2007. return;
  2008. }
  2009. const char * name = ggml_get_name(tensor);
  2010. uint32_t name_len = strlen(name);
  2011. uint32_t nd = tensor->n_dims;
  2012. uint32_t ne[4] = { (uint32_t)tensor->ne[0],
  2013. (uint32_t)tensor->ne[1],
  2014. (uint32_t)tensor->ne[2],
  2015. (uint32_t)tensor->ne[3] };
  2016. file->write_u32(nd);
  2017. file->write_u32(name_len);
  2018. file->write_u32(tensor->type);
  2019. file->write_raw(ne, sizeof(ne[0]) * nd);
  2020. file->write_raw(name, name_len);
  2021. file->seek(-file->tell() & 31, SEEK_CUR);
  2022. file->write_raw(tensor->data, ggml_nbytes(tensor));
  2023. }
  2024. void read_tensor(struct llama_file * file, struct ggml_tensor * tensor) {
  2025. int32_t nd = file->read_u32();
  2026. GGML_ASSERT(nd == tensor->n_dims);
  2027. uint32_t name_len = file->read_u32();
  2028. enum ggml_type type = (enum ggml_type) file->read_u32();
  2029. GGML_ASSERT(type == tensor->type);
  2030. uint32_t ne[4];
  2031. file->read_raw(ne, sizeof(ne[0]) * nd);
  2032. for (int i=0; i<nd; ++i) {
  2033. GGML_ASSERT(ne[i] == tensor->ne[i]);
  2034. }
  2035. std::string name = file->read_string(name_len);
  2036. GGML_ASSERT(strncmp(ggml_get_name(tensor), name.c_str(), sizeof(tensor->name)-1) == 0);
  2037. file->seek(-file->tell() & 31, SEEK_CUR);
  2038. file->read_raw(tensor->data, ggml_nbytes(tensor));
  2039. }
  2040. void write_opt_context(struct llama_file * file, struct ggml_opt_context * opt) {
  2041. const uint32_t version = 0;
  2042. GGML_ASSERT(opt->nx >= 0);
  2043. GGML_ASSERT(opt->iter >= 0);
  2044. file->write_u32(version);
  2045. file->write_raw(&opt->params, sizeof(opt->params));
  2046. file->write_raw(&opt->nx, sizeof(opt->nx));
  2047. file->write_raw(&opt->iter, sizeof(opt->iter));
  2048. file->write_u32((uint32_t) opt->just_initialized);
  2049. switch (opt->params.type) {
  2050. case GGML_OPT_ADAM:
  2051. {
  2052. GGML_ASSERT(opt->adam.x != NULL);
  2053. write_tensor(file, opt->adam.x);
  2054. write_tensor(file, opt->adam.g1);
  2055. write_tensor(file, opt->adam.g2);
  2056. write_tensor(file, opt->adam.m);
  2057. write_tensor(file, opt->adam.v);
  2058. write_tensor(file, opt->adam.mh);
  2059. write_tensor(file, opt->adam.vh);
  2060. write_tensor(file, opt->adam.pf);
  2061. file->write_raw(&opt->adam.fx_best, sizeof(opt->adam.fx_best));
  2062. file->write_raw(&opt->adam.fx_prev, sizeof(opt->adam.fx_prev));
  2063. file->write_raw(&opt->adam.n_no_improvement, sizeof(opt->adam.n_no_improvement));
  2064. } break;
  2065. case GGML_OPT_LBFGS:
  2066. {
  2067. GGML_ASSERT(opt->adam.x != NULL);
  2068. write_tensor(file, opt->lbfgs.x);
  2069. write_tensor(file, opt->lbfgs.xp);
  2070. write_tensor(file, opt->lbfgs.g);
  2071. write_tensor(file, opt->lbfgs.gp);
  2072. write_tensor(file, opt->lbfgs.d);
  2073. write_tensor(file, opt->lbfgs.pf);
  2074. write_tensor(file, opt->lbfgs.lmal);
  2075. write_tensor(file, opt->lbfgs.lmys);
  2076. write_tensor(file, opt->lbfgs.lms);
  2077. write_tensor(file, opt->lbfgs.lmy);
  2078. file->write_raw(&opt->lbfgs.fx_best, sizeof(opt->lbfgs.fx_best));
  2079. file->write_raw(&opt->lbfgs.step, sizeof(opt->lbfgs.step));
  2080. file->write_raw(&opt->lbfgs.j, sizeof(opt->lbfgs.j));
  2081. file->write_raw(&opt->lbfgs.k, sizeof(opt->lbfgs.k));
  2082. file->write_raw(&opt->lbfgs.end, sizeof(opt->lbfgs.end));
  2083. file->write_raw(&opt->lbfgs.n_no_improvement, sizeof(opt->lbfgs.n_no_improvement));
  2084. } break;
  2085. }
  2086. }
  2087. void read_opt_context(struct llama_file * file, struct ggml_context * ctx, struct ggml_opt_context * opt) {
  2088. uint32_t version = file->read_u32();
  2089. GGML_ASSERT(version == 0);
  2090. file->read_raw(&opt->params, sizeof(opt->params));
  2091. file->read_raw(&opt->nx, sizeof(opt->nx));
  2092. ggml_opt_init(ctx, opt, opt->params, opt->nx);
  2093. file->read_raw(&opt->iter, sizeof(opt->iter));
  2094. opt->just_initialized = (bool) file->read_u32();
  2095. switch (opt->params.type) {
  2096. case GGML_OPT_ADAM:
  2097. {
  2098. read_tensor(file, opt->adam.x);
  2099. read_tensor(file, opt->adam.g1);
  2100. read_tensor(file, opt->adam.g2);
  2101. read_tensor(file, opt->adam.m);
  2102. read_tensor(file, opt->adam.v);
  2103. read_tensor(file, opt->adam.mh);
  2104. read_tensor(file, opt->adam.vh);
  2105. if (opt->adam.pf) { read_tensor(file, opt->adam.pf); }
  2106. file->read_raw(&opt->adam.fx_best, sizeof(opt->adam.fx_best));
  2107. file->read_raw(&opt->adam.fx_prev, sizeof(opt->adam.fx_prev));
  2108. file->read_raw(&opt->adam.n_no_improvement, sizeof(opt->adam.n_no_improvement));
  2109. } break;
  2110. case GGML_OPT_LBFGS:
  2111. {
  2112. GGML_ASSERT(opt->adam.x != NULL);
  2113. read_tensor(file, opt->lbfgs.x);
  2114. read_tensor(file, opt->lbfgs.xp);
  2115. read_tensor(file, opt->lbfgs.g);
  2116. read_tensor(file, opt->lbfgs.gp);
  2117. read_tensor(file, opt->lbfgs.d);
  2118. if (opt->lbfgs.pf) { read_tensor(file, opt->lbfgs.pf); }
  2119. read_tensor(file, opt->lbfgs.lmal);
  2120. read_tensor(file, opt->lbfgs.lmys);
  2121. read_tensor(file, opt->lbfgs.lms);
  2122. read_tensor(file, opt->lbfgs.lmy);
  2123. file->read_raw(&opt->lbfgs.fx_best, sizeof(opt->lbfgs.fx_best));
  2124. file->read_raw(&opt->lbfgs.step, sizeof(opt->lbfgs.step));
  2125. file->read_raw(&opt->lbfgs.j, sizeof(opt->lbfgs.j));
  2126. file->read_raw(&opt->lbfgs.k, sizeof(opt->lbfgs.k));
  2127. file->read_raw(&opt->lbfgs.end, sizeof(opt->lbfgs.end));
  2128. file->read_raw(&opt->lbfgs.n_no_improvement, sizeof(opt->lbfgs.n_no_improvement));
  2129. } break;
  2130. }
  2131. }
  2132. void save_checkpoint(struct my_llama_model * model, struct ggml_opt_context * opt, const char * filename) {
  2133. struct llama_file file(filename, "wb");
  2134. if (file.fp == NULL) {
  2135. return;
  2136. }
  2137. const uint32_t magic = 'ggcp';
  2138. const uint32_t version = 0;
  2139. file.write_u32(magic);
  2140. file.write_u32(version);
  2141. file.write_u32(model->train_its);
  2142. file.write_u32(model->train_samples);
  2143. file.write_u32(model->train_tokens);
  2144. file.write_u32(model->hparams.n_vocab);
  2145. file.write_u32(model->hparams.n_embd);
  2146. file.write_u32(model->hparams.n_mult);
  2147. file.write_u32(model->hparams.n_head);
  2148. file.write_u32(model->hparams.n_layer);
  2149. file.write_u32(model->hparams.n_rot);
  2150. write_tensor(&file, model->tok_embeddings);
  2151. write_tensor(&file, model->norm);
  2152. write_tensor(&file, model->output);
  2153. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  2154. auto & layer = model->layers[i];
  2155. write_tensor(&file, layer.attention_norm);
  2156. write_tensor(&file, layer.wq);
  2157. write_tensor(&file, layer.wk);
  2158. write_tensor(&file, layer.wv);
  2159. write_tensor(&file, layer.wo);
  2160. write_tensor(&file, layer.ffn_norm);
  2161. write_tensor(&file, layer.w1);
  2162. write_tensor(&file, layer.w2);
  2163. write_tensor(&file, layer.w3);
  2164. }
  2165. write_opt_context(&file, opt);
  2166. }
  2167. bool load_checkpoint(struct my_llama_model * model, struct ggml_opt_context * opt, const char * filename, bool init) {
  2168. struct llama_file file(filename, "rb");
  2169. uint32_t magic;
  2170. uint32_t version;
  2171. uint32_t train_its = 0;
  2172. uint32_t train_samples = 0;
  2173. uint32_t train_tokens = 0;
  2174. if (file.fp) {
  2175. printf("%s: Loading model from '%s'.\n", __func__, filename);
  2176. magic = file.read_u32();
  2177. GGML_ASSERT(magic == 'ggcp');
  2178. version = file.read_u32();
  2179. GGML_ASSERT(version == 0);
  2180. train_its = file.read_u32();
  2181. train_samples = file.read_u32();
  2182. train_tokens = file.read_u32();
  2183. model->hparams.n_vocab = file.read_u32();
  2184. model->hparams.n_embd = file.read_u32();
  2185. model->hparams.n_mult = file.read_u32();
  2186. model->hparams.n_head = file.read_u32();
  2187. model->hparams.n_layer = file.read_u32();
  2188. model->hparams.n_rot = file.read_u32();
  2189. print_params(&model->hparams);
  2190. }
  2191. if (init) {
  2192. init_model(model);
  2193. }
  2194. if (file.fp) {
  2195. model->train_its = train_its;
  2196. model->train_samples = train_samples;
  2197. model->train_tokens = train_tokens;
  2198. }
  2199. printf("%s: Training iterations: %u.\n", __func__, model->train_its);
  2200. printf("%s: Training samples: %u.\n", __func__, model->train_samples);
  2201. printf("%s: Training tokens: %u.\n", __func__, model->train_tokens);
  2202. if (file.fp) {
  2203. read_tensor(&file, model->tok_embeddings);
  2204. read_tensor(&file, model->norm);
  2205. read_tensor(&file, model->output);
  2206. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  2207. auto & layer = model->layers[i];
  2208. read_tensor(&file, layer.attention_norm);
  2209. read_tensor(&file, layer.wq);
  2210. read_tensor(&file, layer.wk);
  2211. read_tensor(&file, layer.wv);
  2212. read_tensor(&file, layer.wo);
  2213. read_tensor(&file, layer.ffn_norm);
  2214. read_tensor(&file, layer.w1);
  2215. read_tensor(&file, layer.w2);
  2216. read_tensor(&file, layer.w3);
  2217. }
  2218. read_opt_context(&file, model->ctx, opt);
  2219. }
  2220. return (file.fp != NULL);
  2221. }
  2222. void save_as_llama_model(struct llama_vocab * vocab, struct my_llama_model * model, const char * filename) {
  2223. struct llama_file file(filename, "wb");
  2224. if (file.fp == NULL) {
  2225. return;
  2226. }
  2227. // write_magic
  2228. file.write_u32(LLAMA_FILE_MAGIC); // magic
  2229. file.write_u32(LLAMA_FILE_VERSION); // version
  2230. // write_hparams
  2231. file.write_u32(model->hparams.n_vocab);
  2232. file.write_u32(model->hparams.n_embd);
  2233. file.write_u32(model->hparams.n_mult);
  2234. file.write_u32(model->hparams.n_head);
  2235. file.write_u32(model->hparams.n_layer);
  2236. file.write_u32(model->hparams.n_rot);
  2237. file.write_u32(LLAMA_FTYPE_ALL_F32);
  2238. // write_vocab
  2239. uint32_t n_vocab = model->hparams.n_vocab;
  2240. for (uint32_t i = 0; i < n_vocab; i++) {
  2241. const auto & token_score = vocab->id_to_token.at(i);
  2242. file.write_u32((uint32_t) token_score.tok.size());
  2243. file.write_raw(token_score.tok.data(), token_score.tok.size());
  2244. file.write_raw(&token_score.score, sizeof(token_score.score));
  2245. }
  2246. // write tensors
  2247. write_tensor(&file, model->tok_embeddings);
  2248. write_tensor(&file, model->norm);
  2249. write_tensor(&file, model->output);
  2250. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  2251. auto & layer = model->layers[i];
  2252. write_tensor(&file, layer.attention_norm);
  2253. write_tensor(&file, layer.wq);
  2254. write_tensor(&file, layer.wk);
  2255. write_tensor(&file, layer.wv);
  2256. write_tensor(&file, layer.wo);
  2257. write_tensor(&file, layer.ffn_norm);
  2258. write_tensor(&file, layer.w1);
  2259. write_tensor(&file, layer.w2);
  2260. write_tensor(&file, layer.w3);
  2261. }
  2262. }
  2263. float cosine_decay(const int decay_steps, const float alpha, int step) {
  2264. if (step > decay_steps) {
  2265. step = decay_steps;
  2266. }
  2267. const float cosine_decay = 0.50f*(1.0f + cosf(3.14159265359f*step/decay_steps));
  2268. const float decay = (1 - alpha)*cosine_decay + alpha;
  2269. return decay;
  2270. }
  2271. float cosine_decay_restart(int decay_steps, const float alpha, int step, float restart_step_mult) {
  2272. while (step > decay_steps) {
  2273. step -= decay_steps;
  2274. decay_steps = (int) restart_step_mult * decay_steps;
  2275. }
  2276. return cosine_decay(decay_steps, alpha, step);
  2277. }
  2278. struct train_params {
  2279. const char * fn_vocab_model;
  2280. const char * fn_train_data;
  2281. const char * fn_checkpoint_in;
  2282. const char * fn_checkpoint_out;
  2283. const char * fn_model_out;
  2284. int seed;
  2285. int n_ctx;
  2286. int n_embd;
  2287. int n_mult;
  2288. int n_head;
  2289. int n_layer;
  2290. int n_rotmax;
  2291. int n_threads;
  2292. int n_batch;
  2293. int n_examples;
  2294. int n_predict;
  2295. int print_info_interval;
  2296. int print_details_interval;
  2297. bool samples_start_after_nl;
  2298. bool use_adam;
  2299. bool use_flash;
  2300. bool use_scratch;
  2301. // only adam
  2302. int warmup;
  2303. int cos_decay_steps;
  2304. float cos_decay_restart;
  2305. float cos_decay_alpha;
  2306. int lbfgs_n_iter;
  2307. int adam_n_iter;
  2308. float adam_alpha;
  2309. float adam_decay;
  2310. int mem_model_gb;
  2311. int mem_compute_gb;
  2312. int mem_compute0_gb;
  2313. int mem_compute1_gb;
  2314. };
  2315. struct train_params get_default_train_params() {
  2316. struct train_params params;
  2317. params.fn_vocab_model = "ggml-vic7b-uncensored-q4_0.bin";
  2318. params.fn_train_data = "shakespeare.txt";
  2319. params.fn_checkpoint_in = "checkpoint.bin";
  2320. params.fn_checkpoint_out = "checkpoint.bin";
  2321. params.fn_model_out = "ggml-checkpoint-f32.bin";
  2322. params.seed = -1;
  2323. params.n_ctx = 128;
  2324. params.n_embd = 256;
  2325. params.n_mult = 256;
  2326. params.n_head = 8;
  2327. params.n_layer = 16;
  2328. params.n_rotmax = 64;
  2329. params.n_threads = 6;
  2330. params.n_batch = 8;
  2331. params.n_examples = 8;
  2332. params.n_predict = 1024;
  2333. params.print_info_interval = 1;
  2334. params.print_details_interval = 2;
  2335. params.samples_start_after_nl = false;
  2336. params.use_adam = true;
  2337. params.use_flash = true;
  2338. params.use_scratch = true;
  2339. // only adam
  2340. params.warmup = 100;
  2341. params.cos_decay_steps = 1000;
  2342. params.cos_decay_restart = 1.1f;
  2343. params.cos_decay_alpha = 0.0f;
  2344. params.lbfgs_n_iter = 16;
  2345. params.adam_n_iter = 16;
  2346. params.adam_alpha = 1e-3;
  2347. params.adam_decay = 1e-3;
  2348. params.mem_model_gb = 2;
  2349. params.mem_compute_gb = 24;
  2350. params.mem_compute0_gb = 8;
  2351. params.mem_compute1_gb = 2;
  2352. return params;
  2353. }
  2354. void train_print_usage(int /*argc*/, char ** argv, const struct train_params * params) {
  2355. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  2356. fprintf(stderr, "\n");
  2357. fprintf(stderr, "options:\n");
  2358. fprintf(stderr, " -h, --help show this help message and exit\n");
  2359. fprintf(stderr, " --vocab-model FNAME model path from which to load vocab (default '%s')\n", params->fn_vocab_model);
  2360. fprintf(stderr, " --train-data FNAME path from which to load training data (default '%s')\n", params->fn_train_data);
  2361. fprintf(stderr, " --checkpoint-in FNAME path from which to load training checkpoint (default '%s')\n", params->fn_checkpoint_in);
  2362. fprintf(stderr, " --checkpoint-out FNAME path to save training checkpoint (default '%s')\n", params->fn_checkpoint_out);
  2363. fprintf(stderr, " --model-out FNAME path to save ggml model (default '%s')\n", params->fn_model_out);
  2364. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  2365. fprintf(stderr, " -c N, --ctx N Context size used during training (default %d)\n", params->n_ctx);
  2366. fprintf(stderr, " --embd N Embedding size used for new models (default %d)\n", params->n_embd);
  2367. fprintf(stderr, " --mult N Mult size used for new models, influences feedforward size. (default %d)\n", params->n_mult);
  2368. fprintf(stderr, " --head N Number of heads for new models (default %d)\n", params->n_head);
  2369. fprintf(stderr, " --layer N Number of layers for new models (default %d)\n", params->n_layer);
  2370. fprintf(stderr, " --rotmax N Maximal number Rope dimensions for new models (default %d)\n", params->n_rotmax);
  2371. fprintf(stderr, " -t N, --threads N Number of threads (default %d)\n", params->n_threads);
  2372. fprintf(stderr, " -b N, --batch N Parallel batch size (default %d)\n", params->n_batch);
  2373. fprintf(stderr, " -n N, --examples N Number of examples to train (default %d)\n", params->n_examples);
  2374. fprintf(stderr, " --predict N Number of tokens to generate after training (default %d)\n", params->n_predict);
  2375. fprintf(stderr, " --print-info-interval N Print infos during training each N examples (default %d)\n", params->print_info_interval);
  2376. fprintf(stderr, " --print-details-interval N Print details during training each N examples (default %d)\n", params->print_details_interval);
  2377. fprintf(stderr, " --samples-after-nl Training samples start after newlines. (default %s)\n", params->samples_start_after_nl ? "on" : "off");
  2378. fprintf(stderr, " --use-lbfgs Use LBFGS optimizer instead of default Adam\n");
  2379. fprintf(stderr, " --use-adam Use Adam optimizer (default)\n");
  2380. fprintf(stderr, " --no-flash Don't use flash attention.\n");
  2381. fprintf(stderr, " --use-flash Use flash attention (default)\n");
  2382. fprintf(stderr, " --no-scratch Don't use scratch buffers\n");
  2383. fprintf(stderr, " --use-scratch Use scratch buffers (default)\n");
  2384. fprintf(stderr, " --warmup N Number of warmup steps (default %d)\n", params->warmup);
  2385. fprintf(stderr, " --cos-decay-steps N Number of cosine decay steps (default %d)\n", params->cos_decay_steps);
  2386. fprintf(stderr, " --cos-decay-restart N Increase of cosine decay steps after restart (default %f)\n", params->cos_decay_restart);
  2387. fprintf(stderr, " --cos-decay-alpha N Cosine decay alpha (default %f)\n", params->cos_decay_alpha);
  2388. fprintf(stderr, " --lbfgs-iter N Maximum number of LBFGS optimization iterations for each batch (default %d)\n", params->lbfgs_n_iter);
  2389. fprintf(stderr, " --adam-iter N Maximum number of Adam optimization iterations for each batch (default %d)\n", params->adam_n_iter);
  2390. fprintf(stderr, " --adam-alpha N Adam learning rate alpha (default %f)\n", params->adam_alpha);
  2391. fprintf(stderr, " --adam-decay N AdamW weight decay. Values greater zero enable AdamW instead of regular Adam. (default %f)\n", params->adam_decay);
  2392. fprintf(stderr, " --mem-model N Memory to allocate for model and cache in gigabytes. (default %d)\n", params->mem_model_gb);
  2393. fprintf(stderr, " --mem-compute N Memory to allocate for compute in gigabytes. (default %d)\n", params->mem_compute_gb);
  2394. fprintf(stderr, " --mem-compute0 N Memory to allocate for compute in gigabytes. (default %d)\n", params->mem_compute0_gb);
  2395. fprintf(stderr, " --mem-compute1 N Memory to allocate for compute in gigabytes. (default %d)\n", params->mem_compute1_gb);
  2396. fprintf(stderr, "\n");
  2397. }
  2398. bool train_params_parse(int argc, char ** argv, struct train_params * params) {
  2399. bool invalid_param = false;
  2400. std::string arg;
  2401. struct train_params default_params = get_default_train_params();
  2402. const std::string arg_prefix = "--";
  2403. for (int i = 1; i < argc; i++) {
  2404. arg = argv[i];
  2405. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  2406. std::replace(arg.begin(), arg.end(), '_', '-');
  2407. }
  2408. if (arg == "--vocab-model") {
  2409. if (++i >= argc) {
  2410. invalid_param = true;
  2411. break;
  2412. }
  2413. params->fn_vocab_model = argv[i];
  2414. } else if (arg == "--train-data") {
  2415. if (++i >= argc) {
  2416. invalid_param = true;
  2417. break;
  2418. }
  2419. params->fn_train_data = argv[i];
  2420. } else if (arg == "--checkpoint-in") {
  2421. if (++i >= argc) {
  2422. invalid_param = true;
  2423. break;
  2424. }
  2425. params->fn_checkpoint_in = argv[i];
  2426. } else if (arg == "--checkpoint-out") {
  2427. if (++i >= argc) {
  2428. invalid_param = true;
  2429. break;
  2430. }
  2431. params->fn_checkpoint_out = argv[i];
  2432. } else if (arg == "--model-out") {
  2433. if (++i >= argc) {
  2434. invalid_param = true;
  2435. break;
  2436. }
  2437. params->fn_model_out = argv[i];
  2438. } else if (arg == "-s" || arg == "--seed") {
  2439. if (++i >= argc) {
  2440. invalid_param = true;
  2441. break;
  2442. }
  2443. params->seed = std::stoi(argv[i]);
  2444. } else if (arg == "-c" || arg == "--ctx") {
  2445. if (++i >= argc) {
  2446. invalid_param = true;
  2447. break;
  2448. }
  2449. params->n_ctx = std::stoi(argv[i]);
  2450. } else if (arg == "--embd") {
  2451. if (++i >= argc) {
  2452. invalid_param = true;
  2453. break;
  2454. }
  2455. params->n_embd = std::stoi(argv[i]);
  2456. } else if (arg == "--mult") {
  2457. if (++i >= argc) {
  2458. invalid_param = true;
  2459. break;
  2460. }
  2461. params->n_mult = std::stoi(argv[i]);
  2462. } else if (arg == "--head") {
  2463. if (++i >= argc) {
  2464. invalid_param = true;
  2465. break;
  2466. }
  2467. params->n_head = std::stoi(argv[i]);
  2468. } else if (arg == "--layer") {
  2469. if (++i >= argc) {
  2470. invalid_param = true;
  2471. break;
  2472. }
  2473. params->n_layer = std::stoi(argv[i]);
  2474. } else if (arg == "--rotmax") {
  2475. if (++i >= argc) {
  2476. invalid_param = true;
  2477. break;
  2478. }
  2479. params->n_rotmax = std::stoi(argv[i]);
  2480. } else if (arg == "-t" || arg == "--threads") {
  2481. if (++i >= argc) {
  2482. invalid_param = true;
  2483. break;
  2484. }
  2485. params->n_threads = std::stoi(argv[i]);
  2486. } else if (arg == "-b" || arg == "--batch") {
  2487. if (++i >= argc) {
  2488. invalid_param = true;
  2489. break;
  2490. }
  2491. params->n_batch = std::stoi(argv[i]);
  2492. } else if (arg == "-n" || arg == "--examples") {
  2493. if (++i >= argc) {
  2494. invalid_param = true;
  2495. break;
  2496. }
  2497. params->n_examples = std::stoi(argv[i]);
  2498. } else if (arg == "--predict") {
  2499. if (++i >= argc) {
  2500. invalid_param = true;
  2501. break;
  2502. }
  2503. params->n_predict = std::stoi(argv[i]);
  2504. } else if (arg == "--print-info-interval") {
  2505. if (++i >= argc) {
  2506. invalid_param = true;
  2507. break;
  2508. }
  2509. params->print_info_interval = std::stoi(argv[i]);
  2510. } else if (arg == "--print-details-interval") {
  2511. if (++i >= argc) {
  2512. invalid_param = true;
  2513. break;
  2514. }
  2515. params->print_details_interval = std::stoi(argv[i]);
  2516. } else if (arg == "--samples-after-nl") {
  2517. params->samples_start_after_nl = true;
  2518. } else if (arg == "--use-lbfgs") {
  2519. params->use_adam = false;
  2520. } else if (arg == "--use-adam") {
  2521. params->use_adam = true;
  2522. } else if (arg == "--no-flash") {
  2523. params->use_flash = false;
  2524. } else if (arg == "--use-flash") {
  2525. params->use_flash = true;
  2526. } else if (arg == "--no-scratch") {
  2527. params->use_scratch = false;
  2528. } else if (arg == "--use-scratch") {
  2529. params->use_scratch = true;
  2530. } else if (arg == "--warmup") {
  2531. if (++i >= argc) {
  2532. invalid_param = true;
  2533. break;
  2534. }
  2535. params->warmup = std::stoi(argv[i]);
  2536. } else if (arg == "--cos-decay-steps") {
  2537. if (++i >= argc) {
  2538. invalid_param = true;
  2539. break;
  2540. }
  2541. params->cos_decay_steps = std::stof(argv[i]);
  2542. } else if (arg == "--cos-decay-restart") {
  2543. if (++i >= argc) {
  2544. invalid_param = true;
  2545. break;
  2546. }
  2547. params->cos_decay_restart = std::stof(argv[i]);
  2548. } else if (arg == "--cos-decay-alpha") {
  2549. if (++i >= argc) {
  2550. invalid_param = true;
  2551. break;
  2552. }
  2553. params->cos_decay_alpha = std::stof(argv[i]);
  2554. } else if (arg == "--lbfgs-iter") {
  2555. if (++i >= argc) {
  2556. invalid_param = true;
  2557. break;
  2558. }
  2559. params->lbfgs_n_iter = std::stoi(argv[i]);
  2560. } else if (arg == "--adam-iter") {
  2561. if (++i >= argc) {
  2562. invalid_param = true;
  2563. break;
  2564. }
  2565. params->adam_n_iter = std::stoi(argv[i]);
  2566. } else if (arg == "--adam-alpha") {
  2567. if (++i >= argc) {
  2568. invalid_param = true;
  2569. break;
  2570. }
  2571. params->adam_alpha = std::stof(argv[i]);
  2572. } else if (arg == "--adam-decay") {
  2573. if (++i >= argc) {
  2574. invalid_param = true;
  2575. break;
  2576. }
  2577. params->adam_decay = std::stof(argv[i]);
  2578. } else if (arg == "--mem-model") {
  2579. if (++i >= argc) {
  2580. invalid_param = true;
  2581. break;
  2582. }
  2583. params->mem_model_gb = std::stoi(argv[i]);
  2584. } else if (arg == "--mem-compute") {
  2585. if (++i >= argc) {
  2586. invalid_param = true;
  2587. break;
  2588. }
  2589. params->mem_compute_gb = std::stoi(argv[i]);
  2590. } else if (arg == "--mem-compute0") {
  2591. if (++i >= argc) {
  2592. invalid_param = true;
  2593. break;
  2594. }
  2595. params->mem_compute0_gb = std::stoi(argv[i]);
  2596. } else if (arg == "--mem-compute1") {
  2597. if (++i >= argc) {
  2598. invalid_param = true;
  2599. break;
  2600. }
  2601. params->mem_compute1_gb = std::stoi(argv[i]);
  2602. } else if (arg == "-h" || arg == "--help") {
  2603. train_print_usage(argc, argv, &default_params);
  2604. exit(0);
  2605. } else {
  2606. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2607. train_print_usage(argc, argv, &default_params);
  2608. exit(1);
  2609. }
  2610. }
  2611. if (invalid_param) {
  2612. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2613. train_print_usage(argc, argv, &default_params);
  2614. exit(1);
  2615. }
  2616. return true;
  2617. }
  2618. int main(int argc, char ** argv) {
  2619. struct train_params params = get_default_train_params();
  2620. if (!train_params_parse(argc, argv, &params)) {
  2621. return 1;
  2622. }
  2623. if (params.seed < 0) {
  2624. params.seed = time(NULL);
  2625. }
  2626. printf("%s: seed: %d\n", __func__, params.seed);
  2627. srand(params.seed);
  2628. struct llama_context_params llama_params = llama_context_default_params();
  2629. llama_params.vocab_only = true;
  2630. struct llama_context * lctx = llama_init_from_file(params.fn_vocab_model, llama_params);
  2631. struct llama_vocab vocab;
  2632. {
  2633. std::vector<const char *> strings;
  2634. std::vector<float> scores;
  2635. int n_vocab = llama_n_vocab(lctx);
  2636. strings.resize(n_vocab, NULL);
  2637. scores.resize(n_vocab, 0);
  2638. n_vocab = llama_get_vocab(lctx, strings.data(), scores.data(), n_vocab);
  2639. GGML_ASSERT(n_vocab == llama_n_vocab(lctx));
  2640. vocab.id_to_token.resize(n_vocab);
  2641. for (int i=0; i<n_vocab; ++i) {
  2642. std::string tok = std::string(strings[i]);
  2643. float score = scores[i];
  2644. vocab.id_to_token[i].tok = tok;
  2645. vocab.id_to_token[i].score = score;
  2646. vocab.token_to_id.emplace(tok, i);
  2647. }
  2648. }
  2649. printf("%s: tokenize training data\n", __func__);
  2650. std::vector<llama_token> train_tokens;
  2651. if (tokenize_file(lctx, params.fn_train_data, train_tokens) < 0) {
  2652. fprintf(stderr, "%s: failed to tokenize file '%s'\n", __func__, params.fn_train_data);
  2653. }
  2654. printf("%s: number of training tokens: %d\n", __func__, (int) train_tokens.size());
  2655. struct my_llama_model model;
  2656. model.hparams.n_vocab = llama_n_vocab(lctx);
  2657. model.hparams.n_ctx = params.n_ctx;
  2658. model.hparams.n_embd = params.n_embd;
  2659. model.hparams.n_mult = params.n_mult;
  2660. model.hparams.n_head = params.n_head;
  2661. model.hparams.n_layer = params.n_layer;
  2662. model.hparams.n_rot = std::min((uint32_t)params.n_rotmax, model.hparams.n_embd / model.hparams.n_head);
  2663. print_params(&model.hparams);
  2664. std::vector<size_t> token_noccurs;
  2665. std::vector<bool> token_notavail;
  2666. token_noccurs.resize(model.hparams.n_vocab, 0);
  2667. token_notavail.resize(model.hparams.n_vocab, true);
  2668. for (int i = 0; i < (int) train_tokens.size(); ++i) {
  2669. ++token_noccurs[train_tokens[i]];
  2670. token_notavail[train_tokens[i]] = false;
  2671. }
  2672. std::vector<float> token_freq;
  2673. token_freq.resize(model.hparams.n_vocab, 0);
  2674. int n_unique_tokens = 0;
  2675. for (int i = 0; i < (int) token_noccurs.size(); ++i) {
  2676. token_freq[i] = (float) token_noccurs[i] / (float) train_tokens.size();
  2677. n_unique_tokens += (token_noccurs[i] > 0) ? 1 : 0;
  2678. }
  2679. printf("%s: number of unique tokens: %d\n", __func__, n_unique_tokens);
  2680. struct my_llama_kv_cache kv_self;
  2681. struct ggml_init_params lcparams;
  2682. lcparams.mem_size = 1024ll*1024ll*1024ll*((size_t) params.mem_model_gb);
  2683. lcparams.mem_buffer = NULL;
  2684. lcparams.no_alloc = false;
  2685. model.ctx = ggml_init(lcparams);
  2686. kv_self.ctx = model.ctx;
  2687. my_llama_sampler sampler;
  2688. int n_tokens = model.hparams.n_ctx;
  2689. int n_vocab = model.hparams.n_vocab;
  2690. int n_batch = params.n_batch;
  2691. struct ggml_opt_context * opt = (struct ggml_opt_context *) alloca(sizeof(struct ggml_opt_context));
  2692. memset(opt, 0, sizeof(struct ggml_opt_context));
  2693. struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
  2694. struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
  2695. opt_params_adam.print_forward_graph = false;
  2696. opt_params_adam.print_backward_graph = false;
  2697. opt_params_adam.n_threads = params.n_threads;
  2698. opt_params_adam.adam.n_iter = params.adam_n_iter;
  2699. opt_params_adam.adam.sched = 1.0f;
  2700. opt_params_adam.adam.alpha = params.adam_alpha;
  2701. opt_params_adam.adam.decay = params.adam_decay;
  2702. opt_params_lbfgs.print_forward_graph = false;
  2703. opt_params_lbfgs.print_backward_graph = false;
  2704. opt_params_lbfgs.n_threads = params.n_threads;
  2705. opt_params_lbfgs.lbfgs.n_iter = params.lbfgs_n_iter;
  2706. opt->ctx = model.ctx;
  2707. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  2708. printf("%s: init model\n", __func__);
  2709. bool existed = load_checkpoint(&model, opt, params.fn_checkpoint_in, true);
  2710. set_param_model(&model);
  2711. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  2712. opt->iter = model.train_its;
  2713. printf("%s: opt iter %d\n", __func__, opt->iter);
  2714. bool from_scratch = !existed;
  2715. if (from_scratch) {
  2716. randomize_model(&model, params.seed, 0.0f, 1.0f, -1.0f, +1.0f);
  2717. }
  2718. init_kv_cache(&kv_self, &model, 1);
  2719. // init_kv_cache(&kv_self, &model, n_batch);
  2720. init_sampler(&sampler, lctx);
  2721. printf("used_mem model+cache: %zu bytes\n", ggml_used_mem(model.ctx));
  2722. // ggml_print_tensor_objects(model.ctx);
  2723. size_t compute_size = 1024ll*1024ll*1024ll*((size_t) params.mem_compute_gb);
  2724. uint8_t * compute_addr = new uint8_t[compute_size];
  2725. size_t size_buf_0 = 1024ll*1024ll*1024ll*((size_t) params.mem_compute0_gb);
  2726. size_t size_buf_1 = 1024ll*1024ll*1024ll*((size_t) params.mem_compute1_gb);
  2727. uint8_t * compute_buf_0 = new uint8_t[size_buf_0];
  2728. uint8_t * compute_buf_1 = new uint8_t[size_buf_1];
  2729. GGML_ASSERT(n_tokens < (int) train_tokens.size());
  2730. std::vector<int> train_samples;
  2731. train_samples.push_back(0);
  2732. for (int i = 1; i < (int) train_tokens.size() - n_tokens; ++i) {
  2733. if (!params.samples_start_after_nl || (train_tokens[i-1] == llama_token_nl())) {
  2734. train_samples.push_back(i);
  2735. }
  2736. }
  2737. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  2738. for (int i = 0; i < (int) train_samples.size(); ++i) {
  2739. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  2740. }
  2741. printf("%s: begin training\n", __func__);
  2742. for (int ex = 0; ex < params.n_examples; ++ex) {
  2743. if (ex*n_batch >= (int) train_samples.size()) {
  2744. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  2745. for (int i = 0; i < (int) train_samples.size(); ++i) {
  2746. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  2747. }
  2748. }
  2749. struct ggml_init_params cparams = {
  2750. /*.mem_size =*/ compute_size,
  2751. /*.mem_buffer =*/ compute_addr,
  2752. /*.no_alloc =*/ false,
  2753. };
  2754. struct ggml_context * ctx0 = ggml_init(cparams);
  2755. struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  2756. //struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  2757. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  2758. struct ggml_tensor * target_logits = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  2759. struct ggml_tensor * target_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  2760. int n_past = 0;
  2761. struct ggml_tensor * gfbuf = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sizeof(struct ggml_cgraph) / ggml_type_size(GGML_TYPE_I32) + (sizeof(struct ggml_cgraph) % ggml_type_size(GGML_TYPE_I32) ? 1 : 0));
  2762. struct ggml_tensor * gbbuf = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sizeof(struct ggml_cgraph) / ggml_type_size(GGML_TYPE_I32) + (sizeof(struct ggml_cgraph) % ggml_type_size(GGML_TYPE_I32) ? 1 : 0));
  2763. memset(gfbuf->data, 0, ggml_nbytes(gfbuf));
  2764. memset(gbbuf->data, 0, ggml_nbytes(gbbuf));
  2765. struct ggml_cgraph * gf = (struct ggml_cgraph *) gfbuf->data;
  2766. struct ggml_cgraph * gb = (struct ggml_cgraph *) gbbuf->data;
  2767. // ggml_cgraph gf = {};
  2768. gf->n_threads = params.n_threads;
  2769. gb->n_threads = params.n_threads;
  2770. get_example_targets_batch(lctx, train_samples.data(), train_samples.size(), train_tokens.data(), train_tokens.size(), ex, tokens_input, target_logits, target_probs);
  2771. GGML_ASSERT(n_past == 0);
  2772. struct ggml_tensor * loss = NULL;
  2773. struct ggml_tensor * logits = NULL;
  2774. if (params.use_scratch) {
  2775. loss = forward_batch_wo_cache_flash_attn_train(
  2776. &model, ctx0,
  2777. gf, gb,
  2778. &logits, tokens_input, target_probs,
  2779. compute_buf_0, compute_buf_1,
  2780. size_buf_0, size_buf_1,
  2781. n_tokens, n_batch);
  2782. } else if (params.use_flash) {
  2783. logits = forward_batch_wo_cache_flash_attn(&model, ctx0, gf, tokens_input, n_tokens, n_batch);
  2784. loss = cross_entropy_loss(ctx0, logits, target_probs);
  2785. ggml_build_forward_expand(gf, loss);
  2786. *gb = ggml_build_backward(ctx0, gf, true);
  2787. } else {
  2788. logits = forward_batch_wo_cache(&model, ctx0, gf, tokens_input, n_tokens, n_batch);
  2789. loss = cross_entropy_loss(ctx0, logits, target_probs);
  2790. ggml_build_forward_expand(gf, loss);
  2791. *gb = ggml_build_backward(ctx0, gf, true);
  2792. }
  2793. ggml_graph_compute(ctx0, gf);
  2794. size_t used_mem_before_opt = ggml_used_mem(ctx0);
  2795. float error_before_opt = ggml_get_f32_1d(loss, 0);
  2796. opt->params.adam.sched = (opt->iter < params.warmup)
  2797. ? (float) opt->iter / (float) params.warmup
  2798. : cosine_decay_restart(
  2799. params.cos_decay_steps,
  2800. params.cos_decay_alpha,
  2801. opt->iter - params.warmup,
  2802. params.cos_decay_restart);
  2803. printf("%s: opt->params.adam.sched %.5f\n", __func__, opt->params.adam.sched);
  2804. ggml_opt_resume_g(ctx0, opt, loss, gf, gb);
  2805. size_t used_mem_after_opt = ggml_used_mem(ctx0);
  2806. model.train_its = opt->iter;
  2807. model.train_samples += n_batch;
  2808. model.train_tokens += n_batch * n_tokens;
  2809. ggml_graph_compute(ctx0, gf);
  2810. float error_after_opt = ggml_get_f32_1d(loss, 0);
  2811. if (params.print_info_interval > 0 && ex % params.print_info_interval == 0) {
  2812. printf("Example %d, opt iter %d\n", ex, opt->iter);
  2813. printf("error_before_opt: %.6f\n", error_before_opt);
  2814. printf("error_after_opt: %.6f\n", error_after_opt);
  2815. printf("used_mem_before_opt: %zu bytes\n", used_mem_before_opt);
  2816. printf("used_mem_after_opt: %zu bytes\n", used_mem_after_opt);
  2817. }
  2818. if (params.print_details_interval > 0 && ex % params.print_details_interval == 0) {
  2819. // set_logits_masked(logits, token_notavail, -1e9);
  2820. for (int i=0; i<n_batch; ++i) {
  2821. init_sampler(&sampler, lctx);
  2822. for (int k=0; k<n_tokens; ++k) {
  2823. int32_t token = sample(&sampler,
  2824. (float *) ((char *) logits->data + i*logits->nb[2] + k*logits->nb[1]),
  2825. (llama_token *) ((char *) tokens_input->data + i*tokens_input->nb[1]),
  2826. k);
  2827. * ((int32_t *) ((char *) after_opt_best_samples->data + i*after_opt_best_samples->nb[1] + k*after_opt_best_samples->nb[0])) = token;
  2828. }
  2829. }
  2830. // printf("probabilities after optimization:\n");
  2831. // print_matrix(after_opt_probs);
  2832. printf("Example:\n---\n");
  2833. print_tokens_batch(lctx, tokens_input);
  2834. printf("\n---\n");
  2835. // printf("best samples after optimization:\n---\n");
  2836. printf("samples after optimization:\n---\n");
  2837. print_tokens_batch(lctx, after_opt_best_samples);
  2838. printf("\n---\n");
  2839. }
  2840. ggml_free(ctx0);
  2841. }
  2842. if (params.n_examples > 0) {
  2843. save_checkpoint(&model, opt, params.fn_checkpoint_out);
  2844. }
  2845. if (strlen(params.fn_model_out) > 0) {
  2846. save_as_llama_model(&vocab, &model, params.fn_model_out);
  2847. }
  2848. {
  2849. int n_gen = params.n_predict;
  2850. int sample_ctx = n_tokens - n_tokens/8;
  2851. sampler.params.temp = 0.2;
  2852. sampler.params.repeat_penalty = 1.1;
  2853. sampler.params.mirostat = 2;
  2854. init_sampler(&sampler, lctx);
  2855. printf("Generating %d tokens.\n", n_gen);
  2856. struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
  2857. struct ggml_tensor * target_logits = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
  2858. struct ggml_tensor * target_probs = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
  2859. get_example_targets(train_samples.data(), train_samples.size(), train_tokens.data(), train_tokens.size(), rand()%train_samples.size(), tokens_input, target_logits, target_probs);
  2860. for (int i=sample_ctx; i<n_tokens; ++i) {
  2861. ggml_set_i32_1d(tokens_input, i, n_vocab/2);
  2862. }
  2863. for (int i=0; i<sample_ctx-1; ++i) {
  2864. print_token(lctx, ggml_get_i32_1d(tokens_input, i));
  2865. }
  2866. printf("---\n");
  2867. for (int i=0; i<n_gen; ++i) {
  2868. struct ggml_init_params cparams = {
  2869. /*.mem_size =*/ compute_size,
  2870. /*.mem_buffer =*/ compute_addr,
  2871. /*.no_alloc =*/ false,
  2872. };
  2873. struct ggml_context * ctx0 = ggml_init(cparams);
  2874. ggml_cgraph gf = {};
  2875. gf.n_threads = params.n_threads;
  2876. int n_past = 0;
  2877. struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, &gf, tokens_input, sample_ctx, n_past);
  2878. ggml_build_forward_expand(&gf, logits);
  2879. ggml_graph_compute(ctx0, &gf);
  2880. //struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
  2881. //struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
  2882. // set_logits_masked(logits, token_notavail, -1e9);
  2883. int token = sample(&sampler,
  2884. (float *) ((char *) logits->data + (sample_ctx-1)*logits->nb[1]),
  2885. (llama_token *) tokens_input->data,
  2886. sample_ctx-1);
  2887. //int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
  2888. // print_row(probs, sample_at);
  2889. print_token(lctx, token);
  2890. lshift_examples(tokens_input, target_logits, target_probs, 1);
  2891. ggml_set_i32_1d(tokens_input, 0, 0);
  2892. ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
  2893. ggml_free(ctx0);
  2894. }
  2895. }
  2896. delete[] compute_addr;
  2897. delete[] compute_buf_0;
  2898. delete[] compute_buf_1;
  2899. ggml_free(model.ctx);
  2900. return 0;
  2901. }