train-text-from-scratch.cpp 144 KB

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