train-text-from-scratch.cpp 144 KB

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