train-text-from-scratch.cpp 144 KB

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