train-text-from-scratch.cpp 144 KB

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