train-text-from-scratch.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. #include "ggml.h"
  2. #include "ggml-alloc.h"
  3. #include "common.h"
  4. #include "llama.h"
  5. #include <unordered_map>
  6. #include <vector>
  7. #include <cassert>
  8. #include <climits>
  9. #include <cstring>
  10. #include <cstdarg>
  11. #include <ctime>
  12. #include <random>
  13. #include <stdexcept>
  14. #include <algorithm>
  15. #include <string>
  16. #if defined(_MSC_VER)
  17. #pragma warning(disable: 4244 4267) // possible loss of data
  18. #endif
  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. struct ggml_tensor * randomize_tensor_normal(struct ggml_tensor * tensor, struct random_normal_distribution * rnd) {
  55. float scale = 1.0f; // xavier
  56. switch (tensor->n_dims) {
  57. case 1:
  58. scale /= sqrtf(tensor->ne[0]);
  59. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  60. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  61. *dst = scale * frand_normal(rnd);
  62. }
  63. break;
  64. case 2:
  65. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  66. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  67. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  68. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  69. *dst = scale * frand_normal(rnd);
  70. }
  71. }
  72. break;
  73. case 3:
  74. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  75. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  76. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  77. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  78. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  79. *dst = scale * frand_normal(rnd);
  80. }
  81. }
  82. }
  83. break;
  84. case 4:
  85. scale /= sqrtf(tensor->ne[0]+tensor->ne[1]);
  86. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  87. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  88. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  89. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  90. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  91. *dst = scale * frand_normal(rnd);
  92. }
  93. }
  94. }
  95. }
  96. break;
  97. default:
  98. assert(false);
  99. };
  100. return tensor;
  101. }
  102. struct ggml_tensor * randomize_tensor_uniform(struct ggml_tensor * tensor, struct random_uniform_distribution * rnd) {
  103. switch (tensor->n_dims) {
  104. case 1:
  105. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  106. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  107. *dst = frand_uniform(rnd);
  108. }
  109. break;
  110. case 2:
  111. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  112. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  113. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  114. *dst = frand_uniform(rnd);
  115. }
  116. }
  117. break;
  118. case 3:
  119. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  120. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  121. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  122. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  123. *dst = frand_uniform(rnd);
  124. }
  125. }
  126. }
  127. break;
  128. case 4:
  129. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  130. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  131. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  132. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  133. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  134. *dst = frand_uniform(rnd);
  135. }
  136. }
  137. }
  138. }
  139. break;
  140. default:
  141. assert(false);
  142. };
  143. return tensor;
  144. }
  145. struct my_llama_hparams {
  146. uint32_t n_vocab = 32000;
  147. uint32_t n_ctx = 512;
  148. uint32_t n_embd = 4096;
  149. uint32_t n_head = 32;
  150. uint32_t n_layer = 32;
  151. uint32_t n_rot = 64;
  152. uint32_t n_ff = 11008;
  153. // float f_norm_eps = 1e-5; // falcon
  154. float f_norm_rms_eps = 1e-5; // llama
  155. float rope_freq_base = 10000.0f;
  156. float rope_freq_scale = 1.0f;
  157. bool operator!=(const my_llama_hparams& other) const {
  158. return memcmp(this, &other, sizeof(my_llama_hparams));
  159. }
  160. };
  161. struct my_llama_layer {
  162. // normalization
  163. struct ggml_tensor * attention_norm;
  164. // attention
  165. struct ggml_tensor * wq;
  166. struct ggml_tensor * wk;
  167. struct ggml_tensor * wv;
  168. struct ggml_tensor * wo;
  169. // normalization
  170. struct ggml_tensor * ffn_norm;
  171. // ff
  172. struct ggml_tensor * w1;
  173. struct ggml_tensor * w2;
  174. struct ggml_tensor * w3;
  175. };
  176. struct my_llama_model {
  177. struct ggml_context * ctx = NULL;
  178. my_llama_hparams hparams;
  179. struct ggml_tensor * tok_embeddings;
  180. struct ggml_tensor * norm;
  181. struct ggml_tensor * output;
  182. std::vector<my_llama_layer> layers;
  183. uint32_t train_its = 0;
  184. uint32_t train_samples = 0;
  185. uint32_t train_tokens = 0;
  186. };
  187. // gguf constants
  188. const char * LLM_KV_OPTIMIZER_TYPE = "optimizer.type";
  189. const char * LLM_KV_OPTIMIZER_TYPE_ADAM = "adam";
  190. const char * LLM_KV_OPTIMIZER_TYPE_LBFGS = "lbfgs";
  191. const char * LLM_KV_OPTIMIZER_FILE_VERSION = "optimizer.file_version";
  192. const char * LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT = "optimizer.convergence_past_count";
  193. const char * LLM_KV_OPTIMIZER_PARAMETER_COUNT = "optimizer.parameter_count";
  194. const char * LLM_KV_OPTIMIZER_ITERATION_COUNT = "optimizer.iteration_count";
  195. const char * LLM_KV_OPTIMIZER_JUST_INITIALIZED = "optimizer.just_initialized";
  196. const char * LLM_KV_OPTIMIZER_ADAM_BEST_LOSS = "optimizer.adam.best_loss";
  197. const char * LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS = "optimizer.adam.previous_loss";
  198. const char * LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT = "optimizer.adam.no_improvement_count";
  199. const char * LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT = "optimizer.lbfgs.approx_hessian_count";
  200. const char * LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS = "optimizer.lbfgs.best_loss";
  201. const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP = "optimizer.lbfgs.line_search_step";
  202. const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J = "optimizer.lbfgs.line_search_j";
  203. const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K = "optimizer.lbfgs.line_search_k";
  204. const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END = "optimizer.lbfgs.line_search_end";
  205. const char * LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT = "optimizer.lbfgs.no_improvement_count";
  206. const char * LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS = "optimizer.adam.first_moments";
  207. const char * LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS = "optimizer.adam.second_moments";
  208. const char * LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES = "optimizer.adam.past_loss_values";
  209. const char * LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS = "optimizer.lbfgs.current_parameters";
  210. const char * LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS = "optimizer.lbfgs.previous_parameters";
  211. const char * LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS = "optimizer.lbfgs.current_gradients";
  212. const char * LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS = "optimizer.lbfgs.previous_gradients";
  213. const char * LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION = "optimizer.lbfgs.search_direction";
  214. const char * LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES = "optimizer.lbfgs.past_loss_values";
  215. const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA = "optimizer.lbfgs.memory_alpha";
  216. const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS = "optimizer.lbfgs.memory_ys";
  217. const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S = "optimizer.lbfgs.memory_s";
  218. const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y = "optimizer.lbfgs.memory_y";
  219. const char * LLM_KV_TRAINING_FILE_VERSION = "training.file_version";
  220. const char * LLM_KV_TRAINING_ITERATION_COUNT = "training.iteration_count";
  221. const char * LLM_KV_TRAINING_SAMPLE_COUNT = "training.sample_count";
  222. const char * LLM_KV_TRAINING_TOKEN_COUNT = "training.token_count";
  223. // gguf constants (sync with gguf.py)
  224. const char * LLM_KV_GENERAL_ARCHITECTURE = "general.architecture";
  225. const char * LLM_KV_GENERAL_FILE_TYPE = "general.file_type";
  226. const char * LLM_KV_CONTEXT_LENGTH = "%s.context_length";
  227. const char * LLM_KV_EMBEDDING_LENGTH = "%s.embedding_length";
  228. const char * LLM_KV_BLOCK_COUNT = "%s.block_count";
  229. const char * LLM_KV_FEED_FORWARD_LENGTH = "%s.feed_forward_length";
  230. const char * LLM_KV_ATTENTION_HEAD_COUNT = "%s.attention.head_count";
  231. const char * LLM_KV_ATTENTION_LAYERNORM_RMS_EPS = "%s.attention.layer_norm_rms_epsilon";
  232. const char * LLM_KV_ROPE_DIMENSION_COUNT = "%s.rope.dimension_count";
  233. const char * LLM_KV_ROPE_FREQ_BASE = "%s.rope.freq_base"; // TODO load in llama.cpp
  234. const char * LLM_KV_ROPE_SCALE_LINEAR = "%s.rope.scale_linear";
  235. const char * LLM_KV_TOKENIZER_MODEL = "tokenizer.ggml.model";
  236. const char * LLM_KV_TOKENIZER_LIST = "tokenizer.ggml.tokens";
  237. const char * LLM_KV_TOKENIZER_TOKEN_TYPE = "tokenizer.ggml.token_type";
  238. const char * LLM_KV_TOKENIZER_SCORES = "tokenizer.ggml.scores";
  239. const char * LLM_KV_TOKENIZER_MERGES = "tokenizer.ggml.merges";
  240. const char * LLM_KV_TOKENIZER_BOS_ID = "tokenizer.ggml.bos_token_id";
  241. const char * LLM_KV_TOKENIZER_EOS_ID = "tokenizer.ggml.eos_token_id";
  242. const char * LLM_KV_TOKENIZER_UNK_ID = "tokenizer.ggml.unknown_token_id";
  243. const char * LLM_KV_TOKENIZER_SEP_ID = "tokenizer.ggml.seperator_token_id";
  244. const char * LLM_KV_TOKENIZER_PAD_ID = "tokenizer.ggml.padding_token_id";
  245. const char * LLM_TENSOR_TOKEN_EMBD = "token_embd";
  246. const char * LLM_TENSOR_OUTPUT_NORM = "output_norm";
  247. const char * LLM_TENSOR_OUTPUT = "output";
  248. const char * LLM_TENSOR_ATTN_NORM = "blk.%d.attn_norm";
  249. const char * LLM_TENSOR_ATTN_Q = "blk.%d.attn_q";
  250. const char * LLM_TENSOR_ATTN_K = "blk.%d.attn_k";
  251. const char * LLM_TENSOR_ATTN_V = "blk.%d.attn_v";
  252. const char * LLM_TENSOR_ATTN_OUT = "blk.%d.attn_output";
  253. const char * LLM_TENSOR_FFN_NORM = "blk.%d.ffn_norm";
  254. const char * LLM_TENSOR_FFN_GATE = "blk.%d.ffn_gate";
  255. const char * LLM_TENSOR_FFN_DOWN = "blk.%d.ffn_down";
  256. const char * LLM_TENSOR_FFN_UP = "blk.%d.ffn_up";
  257. void print_params(struct my_llama_hparams * params) {
  258. printf("%s: n_vocab: %d\n", __func__, params->n_vocab);
  259. printf("%s: n_ctx: %d\n", __func__, params->n_ctx);
  260. printf("%s: n_embd: %d\n", __func__, params->n_embd);
  261. printf("%s: n_head: %d\n", __func__, params->n_head);
  262. printf("%s: n_ff: %d\n", __func__, params->n_ff);
  263. printf("%s: n_layer: %d\n", __func__, params->n_layer);
  264. printf("%s: n_rot: %d\n", __func__, params->n_rot);
  265. }
  266. void init_model(struct my_llama_model * model) {
  267. const auto & hparams = model->hparams;
  268. const uint32_t n_embd = hparams.n_embd;
  269. const uint32_t n_layer = hparams.n_layer;
  270. const uint32_t n_vocab = hparams.n_vocab;
  271. const uint32_t n_ff = hparams.n_ff;
  272. struct ggml_context * ctx = model->ctx;
  273. model->train_its = 0;
  274. model->train_samples = 0;
  275. model->train_tokens = 0;
  276. std::vector<char> tn_buf;
  277. tn_buf.resize(GGML_MAX_NAME);
  278. auto tn = [&tn_buf](const char * key) -> const char * {
  279. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", key);
  280. return tn_buf.data();
  281. };
  282. auto tni = [&tn_buf](const char * key, int bid) -> const char * {
  283. snprintf(tn_buf.data(), tn_buf.size(), key, bid);
  284. std::string s = tn_buf.data();
  285. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", s.c_str());
  286. return tn_buf.data();
  287. };
  288. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  289. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  290. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  291. ggml_set_name(model->tok_embeddings, tn(LLM_TENSOR_TOKEN_EMBD));
  292. ggml_set_name(model->norm, tn(LLM_TENSOR_OUTPUT_NORM));
  293. ggml_set_name(model->output, tn(LLM_TENSOR_OUTPUT));
  294. model->layers.resize(n_layer);
  295. for (uint32_t i = 0; i < n_layer; ++i) {
  296. auto & layer = model->layers[i];
  297. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  298. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  299. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  300. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  301. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  302. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  303. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  304. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd);
  305. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  306. ggml_set_name(layer.attention_norm, tni(LLM_TENSOR_ATTN_NORM, i));
  307. ggml_set_name(layer.wq, tni(LLM_TENSOR_ATTN_Q, i));
  308. ggml_set_name(layer.wk, tni(LLM_TENSOR_ATTN_K, i));
  309. ggml_set_name(layer.wv, tni(LLM_TENSOR_ATTN_V, i));
  310. ggml_set_name(layer.wo, tni(LLM_TENSOR_ATTN_OUT, i));
  311. ggml_set_name(layer.ffn_norm, tni(LLM_TENSOR_FFN_NORM, i));
  312. ggml_set_name(layer.w1, tni(LLM_TENSOR_FFN_GATE, i));
  313. ggml_set_name(layer.w2, tni(LLM_TENSOR_FFN_DOWN, i));
  314. ggml_set_name(layer.w3, tni(LLM_TENSOR_FFN_UP, i));
  315. }
  316. }
  317. void set_param_model(struct my_llama_model * model) {
  318. const auto& hparams = model->hparams;
  319. const uint32_t n_layer = hparams.n_layer;
  320. struct ggml_context* ctx = model->ctx;
  321. ggml_set_param(ctx, model->tok_embeddings);
  322. ggml_set_param(ctx, model->norm);
  323. ggml_set_param(ctx, model->output);
  324. for (uint32_t i = 0; i < n_layer; ++i) {
  325. auto & layer = model->layers[i];
  326. ggml_set_param(ctx, layer.attention_norm);
  327. ggml_set_param(ctx, layer.wq);
  328. ggml_set_param(ctx, layer.wk);
  329. ggml_set_param(ctx, layer.wv);
  330. ggml_set_param(ctx, layer.wo);
  331. ggml_set_param(ctx, layer.ffn_norm);
  332. ggml_set_param(ctx, layer.w1);
  333. ggml_set_param(ctx, layer.w2);
  334. ggml_set_param(ctx, layer.w3);
  335. }
  336. }
  337. void randomize_model(struct my_llama_model * model, int seed, float mean, float std, float min, float max) {
  338. const auto & hparams = model->hparams;
  339. const uint32_t n_layer = hparams.n_layer;
  340. struct random_normal_distribution rnd;
  341. init_random_normal_distribution(&rnd, seed, mean, std, min, max);
  342. randomize_tensor_normal(model->tok_embeddings, &rnd);
  343. randomize_tensor_normal(model->norm, &rnd);
  344. randomize_tensor_normal(model->output, &rnd);
  345. for (uint32_t i = 0; i < n_layer; ++i) {
  346. auto & layer = model->layers[i];
  347. randomize_tensor_normal(layer.attention_norm, &rnd);
  348. randomize_tensor_normal(layer.wq, &rnd);
  349. randomize_tensor_normal(layer.wk, &rnd);
  350. randomize_tensor_normal(layer.wv, &rnd);
  351. randomize_tensor_normal(layer.wo, &rnd);
  352. randomize_tensor_normal(layer.ffn_norm, &rnd);
  353. randomize_tensor_normal(layer.w1, &rnd);
  354. randomize_tensor_normal(layer.w2, &rnd);
  355. randomize_tensor_normal(layer.w3, &rnd);
  356. }
  357. }
  358. void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
  359. GGML_ASSERT(tensor->n_dims == 1);
  360. GGML_ASSERT(tensor->ne[0] == ne0);
  361. }
  362. void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
  363. GGML_ASSERT(tensor->n_dims == 2);
  364. GGML_ASSERT(tensor->ne[0] == ne0);
  365. GGML_ASSERT(tensor->ne[1] == ne1);
  366. }
  367. void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
  368. GGML_ASSERT(tensor->n_dims == 3);
  369. GGML_ASSERT(tensor->ne[0] == ne0);
  370. GGML_ASSERT(tensor->ne[1] == ne1);
  371. GGML_ASSERT(tensor->ne[2] == ne2);
  372. }
  373. void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  374. GGML_ASSERT(tensor->n_dims == 4);
  375. GGML_ASSERT(tensor->ne[0] == ne0);
  376. GGML_ASSERT(tensor->ne[1] == ne1);
  377. GGML_ASSERT(tensor->ne[2] == ne2);
  378. GGML_ASSERT(tensor->ne[3] == ne3);
  379. }
  380. static size_t hash(void * p) {
  381. return (size_t)p % GGML_GRAPH_HASHTABLE_SIZE;
  382. }
  383. static size_t hash_find(void * hash_table[], void * p) {
  384. size_t h = hash(p);
  385. // linear probing
  386. size_t i = h;
  387. while (hash_table[i] != NULL && hash_table[i] != p) {
  388. i = (i + 1) % GGML_GRAPH_HASHTABLE_SIZE;
  389. if (i == h) {
  390. // visited all hash table entries -> not found
  391. return GGML_GRAPH_HASHTABLE_SIZE;
  392. }
  393. }
  394. return i;
  395. }
  396. static bool hash_insert(void * hash_table[], void * p) {
  397. //size_t h = hash(p);
  398. size_t i = hash_find(hash_table, p);
  399. GGML_ASSERT(i < GGML_GRAPH_HASHTABLE_SIZE); // assert that not full
  400. if (hash_table[i] == p) {
  401. return true;
  402. }
  403. // insert
  404. GGML_ASSERT(hash_table[i] == NULL);
  405. hash_table[i] = p;
  406. return false;
  407. }
  408. static bool hash_contains(void * hash_table[], void * p) {
  409. size_t i = hash_find(hash_table, p);
  410. return (i < GGML_GRAPH_HASHTABLE_SIZE) && (hash_table[i] == p);
  411. }
  412. struct hash_map {
  413. void * keys[GGML_GRAPH_HASHTABLE_SIZE];
  414. void * vals[GGML_GRAPH_HASHTABLE_SIZE];
  415. };
  416. //static const size_t HASH_MAP_SIZE = sizeof(struct hash_map);
  417. struct hash_map * new_hash_map() {
  418. struct hash_map * result = new struct hash_map;
  419. for (int i=0; i<GGML_GRAPH_HASHTABLE_SIZE; ++i) {
  420. result->keys[i] = NULL;
  421. result->vals[i] = NULL;
  422. }
  423. return result;
  424. };
  425. void free_hash_map(struct hash_map * map) {
  426. delete map;
  427. }
  428. static bool ggml_is_view(struct ggml_tensor * t) {
  429. return t->op == GGML_OP_RESHAPE || t->op == GGML_OP_VIEW || t->op == GGML_OP_TRANSPOSE ||
  430. t->op == GGML_OP_PERMUTE || t->op == GGML_OP_CPY;
  431. }
  432. static struct ggml_tensor * get_view_parent(struct ggml_tensor * t) {
  433. switch (t->op) {
  434. case GGML_OP_PERMUTE:
  435. case GGML_OP_RESHAPE:
  436. case GGML_OP_TRANSPOSE:
  437. case GGML_OP_VIEW:
  438. return t->src[0];
  439. case GGML_OP_CPY:
  440. return t->src[1];
  441. default:
  442. return NULL;
  443. }
  444. }
  445. static struct ggml_tensor * get_view_source(struct ggml_tensor * t) {
  446. struct ggml_tensor * parent = t;
  447. do {
  448. parent = get_view_parent(parent);
  449. } while (ggml_is_view(parent));
  450. return parent;
  451. }
  452. struct ggml_tensor * ggml_recompute_graph_node(
  453. struct ggml_context * ctx,
  454. struct ggml_cgraph * graph,
  455. struct hash_map * replacements,
  456. struct ggml_tensor * node) {
  457. if (node == NULL) {
  458. return NULL;
  459. }
  460. if (node->is_param) {
  461. return node;
  462. }
  463. if (!hash_contains(graph->visited_hash_table, node)) {
  464. return node;
  465. }
  466. int count_children = 0;
  467. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  468. if (node->src[k]) {
  469. ++count_children;
  470. }
  471. }
  472. if (count_children == 0) {
  473. return node;
  474. }
  475. size_t i = hash_find(replacements->keys, node);
  476. GGML_ASSERT(i < GGML_GRAPH_HASHTABLE_SIZE); // assert that not full
  477. if (replacements->keys[i] == node) {
  478. return (struct ggml_tensor *) replacements->vals[i];
  479. }
  480. struct ggml_tensor * clone = ggml_new_tensor(ctx, node->type, node->n_dims, node->ne);
  481. // insert clone into replacements
  482. GGML_ASSERT(replacements->keys[i] == NULL); // assert that we don't overwrite
  483. replacements->keys[i] = node;
  484. replacements->vals[i] = clone;
  485. clone->op = node->op;
  486. clone->grad = node->grad;
  487. clone->is_param = node->is_param;
  488. clone->extra = node->extra;
  489. for (int k = 0; k < GGML_MAX_DIMS; ++k) {
  490. clone->nb[k] = node->nb[k];
  491. }
  492. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  493. clone->src[k] = ggml_recompute_graph_node(ctx, graph, replacements, node->src[k]);
  494. }
  495. if (ggml_is_view(clone)) {
  496. struct ggml_tensor * source = get_view_source(clone);
  497. GGML_ASSERT(source != NULL);
  498. clone->data = source->data;
  499. }
  500. GGML_ASSERT(sizeof(node->op_params) == sizeof(int32_t) * (GGML_MAX_OP_PARAMS / sizeof(int32_t)));
  501. GGML_ASSERT(sizeof(node->name) == GGML_MAX_NAME);
  502. memcpy(clone->op_params, node->op_params, sizeof(node->op_params));
  503. ggml_format_name(clone, "%s (clone)", ggml_get_name(node));
  504. return clone;
  505. };
  506. void ggml_build_backward_gradient_checkpointing(
  507. struct ggml_context * ctx,
  508. struct ggml_cgraph * gf,
  509. struct ggml_cgraph * gb,
  510. struct ggml_cgraph * gb_tmp,
  511. struct ggml_tensor * * checkpoints,
  512. int n_checkpoints) {
  513. *gb_tmp = *gf;
  514. ggml_build_backward_expand(ctx, gf, gb_tmp, true);
  515. if (n_checkpoints <= 0) {
  516. *gb = *gb_tmp;
  517. return;
  518. }
  519. struct hash_map * replacements = new_hash_map();
  520. // insert checkpoints in replacements
  521. for (int i = 0; i < n_checkpoints; ++i) {
  522. size_t k = hash_find(replacements->keys, checkpoints[i]);
  523. GGML_ASSERT(k < GGML_GRAPH_HASHTABLE_SIZE); // assert that not full
  524. GGML_ASSERT(replacements->keys[k] == NULL); // assert that we don't overwrite
  525. replacements->keys[k] = checkpoints[i];
  526. replacements->vals[k] = checkpoints[i];
  527. }
  528. *gb = *gf;
  529. // rewrite gb_tmp->nodes[gf->n_nodes:gb_tmp->n_nodes],
  530. // replacing references to gb_tmp->nodes[0:gf->n_nodes] ( == gf->nodes[0:gf->n_nodes]),
  531. // by recomputing them from checkpoints
  532. for (int i = gf->n_nodes; i<gb_tmp->n_nodes; ++i) {
  533. struct ggml_tensor * node = gb_tmp->nodes[i];
  534. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  535. // insert new tensors recomputing src, reusing already made replacements,
  536. // remember replacements: remember new tensors with mapping from corresponding gf nodes
  537. // recurse for input tensors,
  538. // unless (i.e. terminating when) input tensors are checkpoints
  539. node->src[k] = ggml_recompute_graph_node(ctx, gf, replacements, node->src[k]);
  540. }
  541. // insert rewritten backward node with replacements made into resulting backward graph gb
  542. ggml_build_forward_expand(gb, node);
  543. }
  544. free_hash_map(replacements);
  545. }
  546. struct ggml_tensor * llama_build_train_graphs(
  547. struct my_llama_model * model,
  548. struct ggml_allocr * alloc,
  549. struct ggml_context * ctx,
  550. struct ggml_cgraph * gf,
  551. struct ggml_cgraph * gb,
  552. struct ggml_cgraph * gb_tmp,
  553. struct ggml_tensor * * logits,
  554. struct ggml_tensor * tokens_input,
  555. struct ggml_tensor * targets,
  556. const int n_tokens,
  557. const int n_batch,
  558. const bool enable_flash_attn,
  559. const bool enable_checkpointing) {
  560. ggml_set_scratch(ctx, { 0, 0, nullptr, });
  561. const int n_past = 0;
  562. const int N = n_tokens;
  563. const auto & hparams = model->hparams;
  564. const int n_ctx = hparams.n_ctx;
  565. const int n_vocab = hparams.n_vocab;
  566. const int n_embd = hparams.n_embd;
  567. const int n_layer = hparams.n_layer;
  568. const int n_head = hparams.n_head;
  569. const int n_rot = hparams.n_rot;
  570. const int n_ff = hparams.n_ff;
  571. const float f_norm_rms_eps = hparams.f_norm_rms_eps;
  572. const float rope_freq_base = hparams.rope_freq_base;
  573. const float rope_freq_scale = hparams.rope_freq_scale;
  574. auto set_name = [](struct ggml_tensor * t, const char * n) {
  575. ggml_set_name(t, n);
  576. if (t->grad) {
  577. ggml_format_name(t->grad, "%s->grad", n);
  578. }
  579. };
  580. // rope has so much parameters that we make a custom function for it
  581. auto rope = [ctx, n_rot, n_ctx, rope_freq_base, rope_freq_scale]
  582. (struct ggml_tensor * t) -> struct ggml_tensor * {
  583. // not capturing these, to silcence warnings
  584. const int n_past = 0;
  585. const int rope_mode = 0;
  586. return ggml_rope_custom(ctx,
  587. t, n_past, n_rot, rope_mode, n_ctx,
  588. rope_freq_base, rope_freq_scale);
  589. };
  590. set_name(tokens_input, "tokens_input");
  591. set_name(targets, "targets");
  592. GGML_ASSERT(tokens_input->type == GGML_TYPE_I32);
  593. struct ggml_tensor * t00 = ggml_reshape_1d(ctx, tokens_input, N*n_batch); set_name(t00, "t00"); assert_shape_1d(t00, N*n_batch);
  594. struct ggml_tensor * t01 = ggml_get_rows(ctx, model->tok_embeddings, t00); set_name(t01, "t01"); assert_shape_2d(t01, n_embd, N*n_batch);
  595. struct ggml_tensor * cur = t01;
  596. std::vector<struct ggml_tensor *> checkpoints;
  597. checkpoints.push_back(tokens_input);
  598. checkpoints.push_back(targets);
  599. checkpoints.push_back(t00);
  600. checkpoints.push_back(t01);
  601. struct ggml_tensor * kv_scale;
  602. if (!enable_flash_attn) {
  603. kv_scale = ggml_new_f32(ctx, 1.0f/sqrtf(float(n_embd)/n_head));
  604. }
  605. for (int il = 0; il < n_layer; ++il) {
  606. struct my_llama_layer & layer = model->layers[il];
  607. struct ggml_tensor * t02 = ggml_rms_norm (ctx, cur, f_norm_rms_eps); set_name(t02, "t02"); assert_shape_2d(t02, n_embd, N*n_batch);
  608. struct ggml_tensor * t03 = ggml_repeat (ctx, layer.attention_norm, t02); set_name(t03, "t03"); assert_shape_2d(t03, n_embd, N*n_batch);
  609. struct ggml_tensor * t04 = ggml_mul (ctx, t03, t02); set_name(t04, "t04"); assert_shape_2d(t04, n_embd, N*n_batch);
  610. struct ggml_tensor * t05 = ggml_mul_mat (ctx, layer.wq, t04); set_name(t05, "t05"); assert_shape_2d(t05, n_embd, N*n_batch);
  611. struct ggml_tensor * t06 = ggml_reshape_4d (ctx, t05, n_embd/n_head, n_head, N, n_batch); set_name(t06, "t06"); assert_shape_4d(t06, n_embd/n_head, n_head, N, n_batch);
  612. struct ggml_tensor * t07 = rope (t06); set_name(t07, "t07"); assert_shape_4d(t07, n_embd/n_head, n_head, N, n_batch);
  613. struct ggml_tensor * t08 = ggml_mul_mat (ctx, layer.wk, t04); set_name(t08, "t08"); assert_shape_2d(t08, n_embd, N*n_batch);
  614. struct ggml_tensor * t09 = ggml_reshape_4d (ctx, t08, n_embd/n_head, n_head, N, n_batch); set_name(t09, "t09"); assert_shape_4d(t09, n_embd/n_head, n_head, N, n_batch);
  615. struct ggml_tensor * t10 = rope (t09); set_name(t10, "t10"); assert_shape_4d(t10, n_embd/n_head, n_head, N, n_batch);
  616. struct ggml_tensor * t11 = ggml_mul_mat (ctx, t04, layer.wv); set_name(t11, "t11"); assert_shape_2d(t11, N*n_batch, n_embd);
  617. struct ggml_tensor * t12 = ggml_reshape_4d (ctx, t11, N, n_batch, n_embd/n_head, n_head); set_name(t12, "t12"); assert_shape_4d(t12, N, n_batch, n_embd/n_head, n_head);
  618. struct ggml_tensor * t13 = ggml_permute (ctx, t07, 0, 2, 1, 3); set_name(t13, "t13"); assert_shape_4d(t13, n_embd/n_head, N, n_head, n_batch);
  619. struct ggml_tensor * t14 = ggml_permute (ctx, t10, 0, 2, 1, 3); set_name(t14, "t14"); assert_shape_4d(t14, n_embd/n_head, N, n_head, n_batch);
  620. struct ggml_tensor * t15 = ggml_permute (ctx, t12, 0, 3, 1, 2); set_name(t15, "t15"); assert_shape_4d(t15, N, n_embd/n_head, n_head, n_batch);
  621. struct ggml_tensor * t16;
  622. if (enable_flash_attn) {
  623. t16 = ggml_flash_attn(ctx, t13, t14, t15, true); set_name(t16, "t16"); assert_shape_4d(t16, n_embd/n_head, N, n_head, n_batch);
  624. } else {
  625. struct ggml_tensor * t16_0 = ggml_mul_mat (ctx, t14, t13); set_name(t16_0, "t16_0"); assert_shape_4d(t16_0, N, N, n_head, n_batch);
  626. struct ggml_tensor * t16_1 = ggml_scale_inplace (ctx, t16_0, kv_scale); set_name(t16_1, "t16_1"); assert_shape_4d(t16_1, N, N, n_head, n_batch);
  627. struct ggml_tensor * t16_2 = ggml_diag_mask_inf_inplace(ctx, t16_1, n_past); set_name(t16_2, "t16_2"); assert_shape_4d(t16_2, N, N, n_head, n_batch);
  628. struct ggml_tensor * t16_3 = ggml_soft_max_inplace (ctx, t16_2); set_name(t16_3, "t16_3"); assert_shape_4d(t16_3, N, N, n_head, n_batch);
  629. t16 = ggml_mul_mat(ctx, t15, t16_3); set_name(t16, "t16"); assert_shape_4d(t16, n_embd/n_head, N, n_head, n_batch);
  630. }
  631. struct ggml_tensor * t17 = ggml_permute (ctx, t16, 0, 2, 1, 3); set_name(t17, "t17"); assert_shape_4d(t17, n_embd/n_head, n_head, N, n_batch);
  632. struct ggml_tensor * t18 = ggml_cont (ctx, t17); set_name(t18, "t18"); assert_shape_4d(t18, n_embd/n_head, n_head, N, n_batch);
  633. struct ggml_tensor * t19 = ggml_reshape_2d (ctx, t18, n_embd, N*n_batch); set_name(t19, "t19"); assert_shape_2d(t19, n_embd, N*n_batch);
  634. struct ggml_tensor * t20 = ggml_mul_mat (ctx, layer.wo, t19); set_name(t20, "t20"); assert_shape_2d(t20, n_embd, N*n_batch);
  635. struct ggml_tensor * t21 = ggml_add (ctx, t20, cur); set_name(t21, "t21"); assert_shape_2d(t21, n_embd, N*n_batch);
  636. struct ggml_tensor * t22 = ggml_rms_norm (ctx, t21, f_norm_rms_eps); set_name(t22, "t22"); assert_shape_2d(t22, n_embd, N*n_batch);
  637. struct ggml_tensor * t23 = ggml_repeat (ctx, layer.ffn_norm, t22); set_name(t23, "t23"); assert_shape_2d(t23, n_embd, N*n_batch);
  638. struct ggml_tensor * t24 = ggml_mul (ctx, t23, t22); set_name(t24, "t24"); assert_shape_2d(t24, n_embd, N*n_batch);
  639. struct ggml_tensor * t25 = ggml_mul_mat (ctx, layer.w3, t24); set_name(t25, "t25"); assert_shape_2d(t25, n_ff, N*n_batch);
  640. struct ggml_tensor * t26 = ggml_mul_mat (ctx, layer.w1, t24); set_name(t26, "t26"); assert_shape_2d(t26, n_ff, N*n_batch);
  641. struct ggml_tensor * t27 = ggml_silu (ctx, t26); set_name(t27, "t27"); assert_shape_2d(t27, n_ff, N*n_batch);
  642. struct ggml_tensor * t28 = ggml_mul (ctx, t27, t25); set_name(t28, "t28"); assert_shape_2d(t28, n_ff, N*n_batch);
  643. struct ggml_tensor * t29 = ggml_mul_mat (ctx, layer.w2, t28); set_name(t29, "t29"); assert_shape_2d(t29, n_embd, N*n_batch);
  644. struct ggml_tensor * t30 = ggml_add (ctx, t29, t21); set_name(t30, "t30"); assert_shape_2d(t30, n_embd, N*n_batch);
  645. cur = t30;
  646. checkpoints.push_back(cur);
  647. }
  648. struct ggml_tensor * t31 = ggml_rms_norm (ctx, cur, f_norm_rms_eps); set_name(t31, "t31"); assert_shape_2d(t31, n_embd, N*n_batch);
  649. struct ggml_tensor * t32 = ggml_repeat (ctx, model->norm, t31); set_name(t32, "t32"); assert_shape_2d(t32, n_embd, N*n_batch);
  650. struct ggml_tensor * t33 = ggml_mul (ctx, t32, t31); set_name(t33, "t33"); assert_shape_2d(t33, n_embd, N*n_batch);
  651. struct ggml_tensor * t34 = ggml_mul_mat (ctx, model->output, t33); set_name(t34, "t34"); assert_shape_2d(t34, n_vocab, N*n_batch);
  652. struct ggml_tensor * t35 = ggml_reshape_3d (ctx, t34, n_vocab, N, n_batch); set_name(t35, "t35"); assert_shape_3d(t35, n_vocab, N, n_batch);
  653. struct ggml_tensor * t36 = ggml_cross_entropy_loss(ctx, t35, targets); set_name(t36, "t36"); assert_shape_1d(t36, 1);
  654. checkpoints.push_back(t31);
  655. checkpoints.push_back(t32);
  656. checkpoints.push_back(t33);
  657. checkpoints.push_back(t34);
  658. checkpoints.push_back(t35);
  659. checkpoints.push_back(t36);
  660. ggml_build_forward_expand(gf, t36);
  661. if (enable_checkpointing) {
  662. ggml_build_backward_gradient_checkpointing(ctx, gf, gb, gb_tmp, checkpoints.data(), (int) checkpoints.size());
  663. } else {
  664. *gb = *gf;
  665. ggml_build_backward_expand(ctx, gf, gb, true);
  666. }
  667. if (alloc) {
  668. // make sure some tensors are not reallocated by inserting new temporary nodes depending on them
  669. int n_leafs_before = gb->n_leafs;
  670. int n_nodes_before = gb->n_nodes;
  671. struct ggml_tensor * one = ggml_new_f32(ctx, 1.0f);
  672. // output tensors
  673. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t35, one));
  674. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36, one));
  675. // input gradient
  676. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36->grad, one));
  677. GGML_ASSERT(t36->grad->data == NULL && !ggml_is_view(t36->grad));
  678. ggml_allocr_alloc(alloc, t36->grad);
  679. // gradient tensors (will be set to zero by ggml_graph_reset)
  680. // pinning these produces large unnecessary memory overhead, which will be resolved by PR 2632
  681. for (int i = 0; i < gf->n_nodes; ++i) {
  682. if (!gf->grads[i]) continue;
  683. if (gf->grads[i]->data == NULL && !ggml_is_view(gf->grads[i])) {
  684. ggml_allocr_alloc(alloc, gf->grads[i]);
  685. }
  686. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, gf->grads[i], one));
  687. }
  688. // allocating checkpoints in one block to reduce memory fragmentation
  689. // note: they will be freed in reverse order
  690. for (int i = 0; i < (int) checkpoints.size(); ++i) {
  691. if (checkpoints[i]->data == NULL && !ggml_is_view(checkpoints[i])) {
  692. ggml_allocr_alloc(alloc, checkpoints[i]);
  693. }
  694. }
  695. //int n_leafs_after = gb->n_leafs;
  696. //int n_nodes_after = gb->n_nodes;
  697. ggml_allocr_alloc_graph(alloc, gb);
  698. // remove the additional nodes and leafs
  699. for (int i = n_leafs_before; i < gb->n_leafs; ++i) {
  700. gb->leafs[i] = NULL;
  701. }
  702. for (int i = n_nodes_before; i < gb->n_nodes; ++i) {
  703. gb->nodes[i] = NULL;
  704. }
  705. gb->n_leafs = n_leafs_before;
  706. gb->n_nodes = n_nodes_before;
  707. }
  708. *logits = t35;
  709. return t36;
  710. }
  711. void set_f32_3d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int64_t i2, float value) {
  712. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  713. *ptr = value;
  714. }
  715. void set_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, float value) {
  716. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  717. *ptr = value;
  718. }
  719. void set_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int32_t value) {
  720. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  721. *ptr = value;
  722. }
  723. float get_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  724. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  725. return *ptr;
  726. }
  727. int32_t get_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  728. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  729. return *ptr;
  730. }
  731. void print_row(struct ggml_tensor * probs, int i) {
  732. for (int k = 0; k < probs->ne[0]; ++k) {
  733. float p = get_f32_2d(probs, k, i);
  734. printf(" %.2f", p);
  735. }
  736. printf("\n");
  737. }
  738. void print_matrix(struct ggml_tensor * probs) {
  739. assert(probs->n_dims == 2);
  740. for (int i = 0; i < probs->ne[1]; ++i) {
  741. for (int k = 0; k < probs->ne[0]; ++k) {
  742. float p = get_f32_2d(probs, k, i);
  743. printf(" %.2f", p);
  744. }
  745. printf("\n");
  746. }
  747. }
  748. 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) {
  749. int n_tokens = tokens_input->ne[0];
  750. int n_vocab = target_logits->ne[0];
  751. size_t sample = train_samples[example_id % n_train_samples];
  752. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  753. ggml_set_f32(target_logits, -1.0f/n_vocab);
  754. ggml_set_f32(target_probs, 0.0f);
  755. ggml_set_i32_1d(tokens_input, 0, llama_token_bos(lctx));
  756. for (int i=1; i<n_tokens+1; ++i) {
  757. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  758. set_f32_2d(target_logits, token, i-1, +1.0f);
  759. set_f32_2d(target_probs, token, i-1, +1.0f);
  760. if (i<n_tokens) {
  761. ggml_set_i32_1d(tokens_input, i, token);
  762. }
  763. }
  764. }
  765. 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) {
  766. GGML_ASSERT(tokens_input->n_dims == 2);
  767. GGML_ASSERT(target_logits->n_dims == 3);
  768. GGML_ASSERT(target_probs->n_dims == 3);
  769. int n_vocab = target_logits->ne[0];
  770. int n_tokens = tokens_input->ne[0];
  771. int n_batch = tokens_input->ne[1];
  772. GGML_ASSERT(n_tokens == target_logits->ne[1]);
  773. GGML_ASSERT(n_batch == target_logits->ne[2]);
  774. GGML_ASSERT(n_vocab == target_probs->ne[0]);
  775. GGML_ASSERT(n_tokens == target_probs->ne[1]);
  776. GGML_ASSERT(n_batch == target_probs->ne[2]);
  777. ggml_set_f32(target_logits, -1.0f/n_vocab);
  778. ggml_set_f32(target_probs, 0.0f);
  779. // printf("%s: example_id=%d n_batch=%d n_train_samples=%zu\n", __func__, example_id, n_batch, n_train_samples);
  780. for (int k=0; k<n_batch; ++k) {
  781. // printf("%s: batch %d\n", __func__, k);
  782. size_t sample_idx = (example_id*n_batch + k) % n_train_samples;
  783. size_t sample = train_samples[sample_idx];
  784. // printf("%s: sample_idx=%zu sample=%zu\n", __func__, sample_idx, sample);
  785. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  786. set_i32_2d(tokens_input, 0, k, llama_token_bos(lctx));
  787. for (int i=1; i<n_tokens+1; ++i) {
  788. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  789. set_f32_3d(target_logits, token, i-1, k, +1.0f);
  790. set_f32_3d(target_probs, token, i-1, k, +1.0f);
  791. if (i<n_tokens) {
  792. set_i32_2d(tokens_input, i, k, token);
  793. }
  794. }
  795. }
  796. }
  797. #ifdef __GNUC__
  798. #ifdef __MINGW32__
  799. __attribute__((format(gnu_printf, 1, 2)))
  800. #else
  801. __attribute__((format(printf, 1, 2)))
  802. #endif
  803. #endif
  804. static std::string format(const char * fmt, ...) {
  805. va_list ap, ap2;
  806. va_start(ap, fmt);
  807. va_copy(ap2, ap);
  808. int size = vsnprintf(NULL, 0, fmt, ap);
  809. GGML_ASSERT(size >= 0 && size < INT_MAX);
  810. std::vector<char> buf(size + 1);
  811. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  812. GGML_ASSERT(size2 == size);
  813. va_end(ap2);
  814. va_end(ap);
  815. return std::string(buf.data(), size);
  816. }
  817. int tokenize_file(struct llama_context * lctx, const char * filename, std::vector<llama_token>& out) {
  818. FILE * fp = std::fopen(filename, "rb");
  819. if (fp == NULL) {
  820. return 0;
  821. }
  822. #ifdef _WIN32
  823. GGML_ASSERT(_fseeki64(fp, (__int64) 0, SEEK_END) == 0);
  824. #else
  825. GGML_ASSERT(std::fseek(fp, (long) 0, SEEK_END) == 0);
  826. #endif
  827. size_t size = 0;
  828. #ifdef _WIN32
  829. __int64 ret = _ftelli64(fp);
  830. size = ret;
  831. #else
  832. long ret = std::ftell(fp);
  833. size = ret;
  834. #endif
  835. #ifdef _WIN32
  836. GGML_ASSERT(_fseeki64(fp, (__int64) 0, SEEK_SET) == 0);
  837. #else
  838. GGML_ASSERT(std::fseek(fp, (long) 0, SEEK_SET) == 0);
  839. #endif
  840. std::vector<char> buf;
  841. buf.resize(size+1);
  842. out.resize(size+1);
  843. if (std::fread(buf.data(), size, 1, fp) != 1) {
  844. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  845. }
  846. if (ferror(fp)) {
  847. throw std::runtime_error(format("read error: %s", strerror(errno)));
  848. }
  849. buf[size] = '\0';
  850. int n_tokens = llama_tokenize(lctx, buf.data(), out.data(), out.size(), false);
  851. if (n_tokens < 0) {
  852. out.resize(-n_tokens);
  853. n_tokens = llama_tokenize(lctx, buf.data(), out.data(), out.size(), false);
  854. }
  855. GGML_ASSERT(n_tokens >= 0);
  856. out.resize(n_tokens);
  857. bool verify = false;
  858. if (verify) {
  859. const char * in = buf.data();
  860. const char * end = buf.data() + buf.size();
  861. for (int i = 0; i < (int) out.size(); ++i) {
  862. std::string s = llama_token_to_piece(lctx, out[i]);
  863. int len = s.length();
  864. if (in >= end) {
  865. printf("%s: unexpected end of original text.\n", __func__);
  866. break;
  867. }
  868. const bool matches = (strncmp(in, s.c_str(), len) == 0);
  869. if (matches) {
  870. in += len;
  871. } else {
  872. printf("%s: mismatch: expected '%s', but got '%s'\n", __func__, std::string(in, len).c_str(), s.c_str());
  873. }
  874. }
  875. }
  876. return n_tokens;
  877. }
  878. void shuffle_ints(int * begin, int * end) {
  879. if (end <= begin) return;
  880. int max=begin[0];
  881. for (int i=1; i<end-begin; ++i) {
  882. if (begin[i] > max) {
  883. max = begin[i];
  884. }
  885. }
  886. std::vector<float> vals;
  887. vals.resize(max+1);
  888. for (int i=0; i<max+1; ++i) {
  889. vals[i] = frand();
  890. }
  891. std::sort(begin, end, [&vals](int a, int b){
  892. return vals.at(a) < vals.at(b);
  893. });
  894. }
  895. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  896. { \
  897. const std::string skey(key); \
  898. const int kid = gguf_find_key(ctx, skey.c_str()); \
  899. if (kid >= 0) { \
  900. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  901. if (ktype != (type)) { \
  902. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  903. } \
  904. (dst) = func(ctx, kid); \
  905. } else if (req) { \
  906. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  907. } \
  908. }
  909. bool are_same_layout(struct ggml_tensor * a, struct ggml_tensor * b) {
  910. GGML_ASSERT(a != NULL);
  911. GGML_ASSERT(b != NULL);
  912. GGML_ASSERT(a->type == b->type);
  913. GGML_ASSERT(ggml_are_same_shape(a, b));
  914. GGML_ASSERT(ggml_is_contiguous(a) && ggml_is_contiguous(b));
  915. return true;
  916. }
  917. void read_tensor_by_name(struct ggml_tensor * dst, struct ggml_context * ctx, const char * name) {
  918. if (dst == NULL) {
  919. return;
  920. }
  921. struct ggml_tensor * t = ggml_get_tensor(ctx, name);
  922. GGML_ASSERT(are_same_layout(dst, t));
  923. memcpy(dst->data, t->data, ggml_nbytes(t));
  924. if (strlen(ggml_get_name(dst)) == 0) {
  925. ggml_set_name(dst, name);
  926. }
  927. }
  928. void load_opt_context_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct ggml_opt_context * opt) {
  929. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  930. uint32_t file_version;
  931. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_FILE_VERSION);
  932. GGML_ASSERT(file_version == 0);
  933. GGUF_GET_KEY(fctx, opt->params.past, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT);
  934. GGUF_GET_KEY(fctx, opt->iter, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ITERATION_COUNT);
  935. GGUF_GET_KEY(fctx, opt->just_initialized, gguf_get_val_bool, GGUF_TYPE_BOOL, true, LLM_KV_OPTIMIZER_JUST_INITIALIZED);
  936. uint64_t nx;
  937. GGUF_GET_KEY(fctx, nx, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_OPTIMIZER_PARAMETER_COUNT);
  938. opt->nx = (size_t) nx;
  939. // don't call ggml_opt_init until optimizer type and optimizer specific parameters are know
  940. std::string opt_type;
  941. GGUF_GET_KEY(fctx, opt_type, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_OPTIMIZER_TYPE);
  942. if (opt_type == LLM_KV_OPTIMIZER_TYPE_ADAM) {
  943. opt->params.type = GGML_OPT_ADAM;
  944. GGUF_GET_KEY(fctx, opt->adam.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS);
  945. GGUF_GET_KEY(fctx, opt->adam.fx_prev, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS);
  946. GGUF_GET_KEY(fctx, opt->adam.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT);
  947. GGML_ASSERT(opt->ctx != NULL);
  948. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  949. read_tensor_by_name(opt->adam.m, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  950. read_tensor_by_name(opt->adam.v, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  951. read_tensor_by_name(opt->adam.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  952. } else if (opt_type == LLM_KV_OPTIMIZER_TYPE_LBFGS) {
  953. opt->params.type = GGML_OPT_LBFGS;
  954. GGUF_GET_KEY(fctx, opt->params.lbfgs.m, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT);
  955. GGUF_GET_KEY(fctx, opt->lbfgs.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS);
  956. GGUF_GET_KEY(fctx, opt->lbfgs.step, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP);
  957. GGUF_GET_KEY(fctx, opt->lbfgs.j, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J);
  958. GGUF_GET_KEY(fctx, opt->lbfgs.k, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K);
  959. GGUF_GET_KEY(fctx, opt->lbfgs.end, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END);
  960. GGUF_GET_KEY(fctx, opt->lbfgs.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT);
  961. GGML_ASSERT(opt->ctx != NULL);
  962. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  963. read_tensor_by_name(opt->lbfgs.x, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  964. read_tensor_by_name(opt->lbfgs.xp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  965. read_tensor_by_name(opt->lbfgs.g, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  966. read_tensor_by_name(opt->lbfgs.gp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  967. read_tensor_by_name(opt->lbfgs.d, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  968. read_tensor_by_name(opt->lbfgs.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  969. read_tensor_by_name(opt->lbfgs.lmal, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  970. read_tensor_by_name(opt->lbfgs.lmys, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  971. read_tensor_by_name(opt->lbfgs.lms, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  972. read_tensor_by_name(opt->lbfgs.lmy, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  973. } else {
  974. throw std::runtime_error("unknown optimizer type\n");
  975. }
  976. }
  977. void save_opt_context_gguf(struct gguf_context * fctx, struct ggml_opt_context * opt) {
  978. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_FILE_VERSION, 0);
  979. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT, opt->params.past);
  980. gguf_set_val_u64(fctx, LLM_KV_OPTIMIZER_PARAMETER_COUNT, (uint64_t) opt->nx);
  981. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ITERATION_COUNT, opt->iter);
  982. gguf_set_val_bool(fctx, LLM_KV_OPTIMIZER_JUST_INITIALIZED, opt->just_initialized);
  983. switch (opt->params.type) {
  984. case GGML_OPT_ADAM:
  985. {
  986. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_ADAM);
  987. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS, opt->adam.fx_best);
  988. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS, opt->adam.fx_prev);
  989. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT, opt->adam.n_no_improvement);
  990. ggml_set_name(opt->adam.m, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  991. ggml_set_name(opt->adam.v, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  992. if (opt->adam.pf) {
  993. ggml_set_name(opt->adam.pf, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  994. }
  995. gguf_add_tensor(fctx, opt->adam.m);
  996. gguf_add_tensor(fctx, opt->adam.v);
  997. if (opt->adam.pf) {
  998. gguf_add_tensor(fctx, opt->adam.pf);
  999. }
  1000. } break;
  1001. case GGML_OPT_LBFGS:
  1002. {
  1003. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_LBFGS);
  1004. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT, opt->params.lbfgs.m);
  1005. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS, opt->lbfgs.fx_best);
  1006. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP, opt->lbfgs.step);
  1007. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J, opt->lbfgs.j);
  1008. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K, opt->lbfgs.k);
  1009. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END, opt->lbfgs.end);
  1010. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT, opt->lbfgs.n_no_improvement);
  1011. ggml_set_name(opt->lbfgs.x, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  1012. ggml_set_name(opt->lbfgs.xp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  1013. ggml_set_name(opt->lbfgs.g, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  1014. ggml_set_name(opt->lbfgs.gp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  1015. ggml_set_name(opt->lbfgs.d, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  1016. if (opt->lbfgs.pf) {
  1017. ggml_set_name(opt->lbfgs.pf, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  1018. }
  1019. ggml_set_name(opt->lbfgs.lmal, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  1020. ggml_set_name(opt->lbfgs.lmys, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  1021. ggml_set_name(opt->lbfgs.lms, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  1022. ggml_set_name(opt->lbfgs.lmy, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  1023. gguf_add_tensor(fctx, opt->lbfgs.x);
  1024. gguf_add_tensor(fctx, opt->lbfgs.xp);
  1025. gguf_add_tensor(fctx, opt->lbfgs.g);
  1026. gguf_add_tensor(fctx, opt->lbfgs.gp);
  1027. gguf_add_tensor(fctx, opt->lbfgs.d);
  1028. if (opt->lbfgs.pf) {
  1029. gguf_add_tensor(fctx, opt->lbfgs.pf);
  1030. }
  1031. gguf_add_tensor(fctx, opt->lbfgs.lmal);
  1032. gguf_add_tensor(fctx, opt->lbfgs.lmys);
  1033. gguf_add_tensor(fctx, opt->lbfgs.lms);
  1034. gguf_add_tensor(fctx, opt->lbfgs.lmy);
  1035. } break;
  1036. }
  1037. }
  1038. void load_llama_model_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model) {
  1039. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  1040. std::string arch;
  1041. std::vector<char> keybuf;
  1042. keybuf.resize(512);
  1043. auto kv = [&arch, &keybuf](const char * key) -> const char * {
  1044. snprintf(keybuf.data(), keybuf.size(), key, arch.c_str());
  1045. return keybuf.data();
  1046. };
  1047. std::vector<char> tn_buf;
  1048. tn_buf.resize(GGML_MAX_NAME);
  1049. auto tn = [&tn_buf](const char * key) -> const char * {
  1050. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", key);
  1051. return tn_buf.data();
  1052. };
  1053. auto tni = [&tn_buf](const char * key, int bid) -> const char * {
  1054. snprintf(tn_buf.data(), tn_buf.size(), key, bid);
  1055. std::string s = tn_buf.data();
  1056. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", s.c_str());
  1057. return tn_buf.data();
  1058. };
  1059. GGUF_GET_KEY(fctx, arch, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_GENERAL_ARCHITECTURE);
  1060. GGML_ASSERT(arch == "llama");
  1061. uint32_t ftype_u;
  1062. GGUF_GET_KEY(fctx, ftype_u, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_GENERAL_FILE_TYPE);
  1063. GGML_ASSERT((enum llama_ftype) ftype_u == LLAMA_FTYPE_ALL_F32);
  1064. // n_ctx was not saved in earlier checkpoint file versions, so we make it optional here
  1065. GGUF_GET_KEY(fctx, model->hparams.n_ctx, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_CONTEXT_LENGTH));
  1066. GGUF_GET_KEY(fctx, model->hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1067. GGUF_GET_KEY(fctx, model->hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1068. GGUF_GET_KEY(fctx, model->hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1069. GGUF_GET_KEY(fctx, model->hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1070. model->hparams.n_rot = model->hparams.n_embd / model->hparams.n_head;
  1071. GGUF_GET_KEY(fctx, model->hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1072. float rope_freq_scale = 1.0f;
  1073. GGUF_GET_KEY(fctx, model->hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1074. GGUF_GET_KEY(fctx, model->hparams.rope_freq_base, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1075. GGUF_GET_KEY(fctx, rope_freq_scale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1076. if (rope_freq_scale != 1.0f) {
  1077. model->hparams.rope_freq_scale = 1.0f / rope_freq_scale;
  1078. }
  1079. init_model(model);
  1080. read_tensor_by_name(model->tok_embeddings, f_ggml_ctx, tn(LLM_TENSOR_TOKEN_EMBD));
  1081. read_tensor_by_name(model->norm, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT_NORM));
  1082. read_tensor_by_name(model->output, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT));
  1083. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  1084. auto & layer = model->layers[i];
  1085. read_tensor_by_name(layer.attention_norm, f_ggml_ctx, tni(LLM_TENSOR_ATTN_NORM, i));
  1086. read_tensor_by_name(layer.wq, f_ggml_ctx, tni(LLM_TENSOR_ATTN_Q, i));
  1087. read_tensor_by_name(layer.wk, f_ggml_ctx, tni(LLM_TENSOR_ATTN_K, i));
  1088. read_tensor_by_name(layer.wv, f_ggml_ctx, tni(LLM_TENSOR_ATTN_V, i));
  1089. read_tensor_by_name(layer.wo, f_ggml_ctx, tni(LLM_TENSOR_ATTN_OUT, i));
  1090. read_tensor_by_name(layer.ffn_norm, f_ggml_ctx, tni(LLM_TENSOR_FFN_NORM, i));
  1091. read_tensor_by_name(layer.w1, f_ggml_ctx, tni(LLM_TENSOR_FFN_GATE, i));
  1092. read_tensor_by_name(layer.w2, f_ggml_ctx, tni(LLM_TENSOR_FFN_DOWN, i));
  1093. read_tensor_by_name(layer.w3, f_ggml_ctx, tni(LLM_TENSOR_FFN_UP, i));
  1094. }
  1095. }
  1096. void save_llama_model_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model) {
  1097. const char * arch = "llama";
  1098. enum llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1099. std::vector<char> keybuf;
  1100. keybuf.resize(512);
  1101. auto kv = [arch, &keybuf](const char * key) -> const char * {
  1102. snprintf(keybuf.data(), keybuf.size(), key, arch);
  1103. return keybuf.data();
  1104. };
  1105. // set arch
  1106. gguf_set_val_str(fctx, LLM_KV_GENERAL_ARCHITECTURE, arch);
  1107. gguf_set_val_u32(fctx, LLM_KV_GENERAL_FILE_TYPE, ftype);
  1108. // set hparams
  1109. gguf_set_val_u32(fctx, kv(LLM_KV_CONTEXT_LENGTH), model->hparams.n_ctx );
  1110. gguf_set_val_u32(fctx, kv(LLM_KV_EMBEDDING_LENGTH), model->hparams.n_embd );
  1111. gguf_set_val_u32(fctx, kv(LLM_KV_FEED_FORWARD_LENGTH), model->hparams.n_ff );
  1112. gguf_set_val_u32(fctx, kv(LLM_KV_ATTENTION_HEAD_COUNT), model->hparams.n_head );
  1113. gguf_set_val_u32(fctx, kv(LLM_KV_BLOCK_COUNT), model->hparams.n_layer );
  1114. gguf_set_val_u32(fctx, kv(LLM_KV_ROPE_DIMENSION_COUNT), model->hparams.n_rot );
  1115. gguf_set_val_f32(fctx, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS), model->hparams.f_norm_rms_eps );
  1116. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_FREQ_BASE), model->hparams.rope_freq_base ); // TODO load in llama.cpp
  1117. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_SCALE_LINEAR), 1.0f / model->hparams.rope_freq_scale );
  1118. // set vocab by copying from vocab_model gguf file
  1119. {
  1120. struct gguf_init_params params = {
  1121. /*.no_alloc = */ false,
  1122. /*.ctx = */ NULL,
  1123. };
  1124. struct gguf_context * vctx = gguf_init_from_file(fn_vocab_model, params);
  1125. const int token_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_LIST));
  1126. if (token_idx == -1) {
  1127. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1128. }
  1129. const uint32_t n_vocab = gguf_get_arr_n(vctx, token_idx);
  1130. const int score_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_SCORES));
  1131. if (score_idx == -1) {
  1132. throw std::runtime_error("cannot find tokenizer scores in model file\n");
  1133. }
  1134. const float * scores = (const float * ) gguf_get_arr_data(vctx, score_idx);
  1135. const int toktype_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE));
  1136. if (toktype_idx == -1) {
  1137. throw std::runtime_error("cannot find token type list in GGUF file\n");
  1138. }
  1139. const int * toktypes = (const int * ) gguf_get_arr_data(vctx, toktype_idx);
  1140. std::string tokenizer_name;
  1141. GGUF_GET_KEY(vctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1142. gguf_set_val_str(fctx, kv(LLM_KV_TOKENIZER_MODEL), tokenizer_name.c_str());
  1143. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_SCORES), GGUF_TYPE_FLOAT32, scores, n_vocab);
  1144. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE), GGUF_TYPE_INT32, toktypes, n_vocab);
  1145. int32_t special_bos_id = 1;
  1146. int32_t special_eos_id = 2;
  1147. int32_t special_unk_id = 0;
  1148. int32_t special_sep_id = -1;
  1149. int32_t special_pad_id = -1;
  1150. if (tokenizer_name == "llama") {
  1151. // default special tokens
  1152. special_bos_id = 1;
  1153. special_eos_id = 2;
  1154. special_unk_id = 0;
  1155. special_sep_id = -1;
  1156. special_pad_id = -1;
  1157. } else if (tokenizer_name == "gpt2") {
  1158. // read and copy bpe merges
  1159. const int merges_keyidx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_MERGES));
  1160. if (merges_keyidx == -1) {
  1161. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1162. }
  1163. const int n_merges = gguf_get_arr_n(vctx, merges_keyidx);
  1164. std::vector<const char*> merges;
  1165. merges.resize(n_merges);
  1166. for (int i = 0; i < n_merges; i++) {
  1167. merges[i] = gguf_get_arr_str(vctx, merges_keyidx, i);
  1168. }
  1169. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_MERGES), merges.data(), n_merges);
  1170. // default special tokens
  1171. special_bos_id = 11;
  1172. special_eos_id = 11;
  1173. special_unk_id = -1;
  1174. special_sep_id = -1;
  1175. special_pad_id = -1;
  1176. } else {
  1177. fprintf(stderr, "%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1178. fprintf(stderr, "%s: using default tokenizer: 'llama'", __func__);
  1179. }
  1180. std::vector<const char*> tokens;
  1181. tokens.resize(n_vocab);
  1182. for (uint32_t i = 0; i < n_vocab; i++) {
  1183. tokens[i] = gguf_get_arr_str(vctx, token_idx, i);
  1184. }
  1185. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_LIST), tokens.data(), n_vocab);
  1186. GGUF_GET_KEY(vctx, special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1187. GGUF_GET_KEY(vctx, special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1188. GGUF_GET_KEY(vctx, special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1189. GGUF_GET_KEY(vctx, special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1190. GGUF_GET_KEY(vctx, special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1191. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_BOS_ID), special_bos_id);
  1192. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_EOS_ID), special_eos_id);
  1193. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_UNK_ID), special_unk_id);
  1194. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_SEP_ID), special_sep_id);
  1195. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_PAD_ID), special_pad_id);
  1196. gguf_free(vctx);
  1197. }
  1198. // add tensors
  1199. gguf_add_tensor(fctx, model->tok_embeddings);
  1200. gguf_add_tensor(fctx, model->norm);
  1201. gguf_add_tensor(fctx, model->output);
  1202. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  1203. auto & layer = model->layers[i];
  1204. gguf_add_tensor(fctx, layer.attention_norm);
  1205. gguf_add_tensor(fctx, layer.wq);
  1206. gguf_add_tensor(fctx, layer.wk);
  1207. gguf_add_tensor(fctx, layer.wv);
  1208. gguf_add_tensor(fctx, layer.wo);
  1209. gguf_add_tensor(fctx, layer.ffn_norm);
  1210. gguf_add_tensor(fctx, layer.w1);
  1211. gguf_add_tensor(fctx, layer.w2);
  1212. gguf_add_tensor(fctx, layer.w3);
  1213. }
  1214. }
  1215. void save_llama_model_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model) {
  1216. struct gguf_context * fctx = gguf_init_empty();
  1217. save_llama_model_gguf(fctx, fn_vocab_model, model);
  1218. // write file
  1219. const bool only_meta = false;
  1220. gguf_write_to_file(fctx, filename, only_meta);
  1221. gguf_free(fctx);
  1222. }
  1223. void load_checkpoint_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1224. load_llama_model_gguf(fctx, f_ggml_ctx, model);
  1225. uint32_t file_version;
  1226. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_FILE_VERSION);
  1227. GGML_ASSERT(file_version == 0);
  1228. GGUF_GET_KEY(fctx, model->train_its, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_ITERATION_COUNT);
  1229. GGUF_GET_KEY(fctx, model->train_samples, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_SAMPLE_COUNT);
  1230. GGUF_GET_KEY(fctx, model->train_tokens, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_TOKEN_COUNT);
  1231. load_opt_context_gguf(fctx, f_ggml_ctx, opt);
  1232. }
  1233. void save_checkpoint_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1234. save_llama_model_gguf(fctx, fn_vocab_model, model);
  1235. gguf_set_val_u32(fctx, LLM_KV_TRAINING_FILE_VERSION, 0);
  1236. gguf_set_val_u32(fctx, LLM_KV_TRAINING_ITERATION_COUNT, model->train_its);
  1237. gguf_set_val_u32(fctx, LLM_KV_TRAINING_SAMPLE_COUNT, model->train_samples);
  1238. gguf_set_val_u32(fctx, LLM_KV_TRAINING_TOKEN_COUNT, model->train_tokens);
  1239. save_opt_context_gguf(fctx, opt);
  1240. }
  1241. bool load_checkpoint_file(const char * filename, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1242. struct ggml_context * f_ggml_ctx;
  1243. struct gguf_init_params params;
  1244. params.no_alloc = false;
  1245. params.ctx = &f_ggml_ctx;
  1246. struct gguf_context * fctx = gguf_init_from_file(filename, params);
  1247. if (fctx == NULL) {
  1248. return false;
  1249. }
  1250. load_checkpoint_gguf(fctx, f_ggml_ctx, model, opt);
  1251. return true;
  1252. }
  1253. void save_checkpoint_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1254. struct gguf_context * fctx = gguf_init_empty();
  1255. save_checkpoint_gguf(fctx, fn_vocab_model, model, opt);
  1256. // write file
  1257. const bool only_meta = false;
  1258. gguf_write_to_file(fctx, filename, only_meta);
  1259. gguf_free(fctx);
  1260. }
  1261. float cosine_decay(const int decay_steps, const float minimum, int step) {
  1262. if (step > decay_steps) {
  1263. step = decay_steps;
  1264. }
  1265. const float cosine_decay = 0.50f*(1.0f + cosf(3.14159265359f*step/decay_steps));
  1266. const float decay = (1 - minimum)*cosine_decay + minimum;
  1267. return decay;
  1268. }
  1269. float cosine_decay_restart(int decay_steps, const float minimum, int step, float restart_step_mult, bool enable_restart) {
  1270. if (enable_restart) {
  1271. while (step > decay_steps) {
  1272. step -= decay_steps;
  1273. decay_steps = (int) restart_step_mult * decay_steps;
  1274. }
  1275. }
  1276. return cosine_decay(decay_steps, minimum, step);
  1277. }
  1278. struct train_params {
  1279. const char * fn_vocab_model;
  1280. const char * fn_train_data;
  1281. const char * fn_checkpoint_in;
  1282. const char * fn_checkpoint_out;
  1283. const char * fn_model_out;
  1284. uint32_t seed;
  1285. int n_ctx;
  1286. int n_embd;
  1287. int n_head;
  1288. int n_layer;
  1289. int n_ff;
  1290. int n_threads;
  1291. int n_batch;
  1292. int n_examples;
  1293. float f_norm_rms_eps;
  1294. float rope_freq_base;
  1295. float rope_freq_scale;
  1296. int print_info_interval;
  1297. bool samples_start_after_nl;
  1298. bool use_adam;
  1299. bool use_flash;
  1300. bool use_checkpointing;
  1301. bool use_alloc;
  1302. // only adam
  1303. int warmup;
  1304. int cos_decay_steps;
  1305. float cos_decay_restart;
  1306. float cos_decay_min;
  1307. bool enable_restart;
  1308. int opt_past;
  1309. float opt_delta;
  1310. int opt_max_no_improvement;
  1311. int lbfgs_n_iter;
  1312. int adam_n_iter;
  1313. float adam_alpha;
  1314. float adam_min_alpha;
  1315. float adam_decay;
  1316. int adam_decay_min_ndim;
  1317. float adam_beta1;
  1318. float adam_beta2;
  1319. float adam_gclip;
  1320. float adam_eps_f;
  1321. int mem_model_gb;
  1322. int mem_compute_gb;
  1323. int mem_compute0_gb;
  1324. };
  1325. struct train_params get_default_train_params() {
  1326. struct train_params params;
  1327. params.fn_vocab_model = "ggml-vic7b-uncensored-q4_0.bin";
  1328. params.fn_train_data = "shakespeare.txt";
  1329. params.fn_checkpoint_in = "checkpoint.bin";
  1330. params.fn_checkpoint_out = "checkpoint.bin";
  1331. params.fn_model_out = "ggml-checkpoint-f32.bin";
  1332. params.seed = -1;
  1333. params.n_ctx = 128;
  1334. params.n_embd = 256;
  1335. params.n_head = 8;
  1336. params.n_layer = 16;
  1337. params.n_ff = 768;
  1338. params.n_threads = 6;
  1339. params.n_batch = 8;
  1340. params.n_examples = 1;
  1341. params.f_norm_rms_eps = 1e-5;
  1342. params.rope_freq_base = 10000.0f;
  1343. params.rope_freq_scale = 1.0f;
  1344. params.print_info_interval = 1;
  1345. params.samples_start_after_nl = false;
  1346. params.use_adam = true;
  1347. params.use_flash = true;
  1348. params.use_checkpointing = true;
  1349. params.use_alloc = true;
  1350. params.opt_past = 0;
  1351. params.opt_delta = 1e-5f;
  1352. params.opt_max_no_improvement = 0;
  1353. // only adam
  1354. params.warmup = 100;
  1355. params.cos_decay_steps = 1000;
  1356. params.cos_decay_restart = 1.1f;
  1357. params.cos_decay_min = 0.1f;
  1358. params.enable_restart = false;
  1359. params.lbfgs_n_iter = 256;
  1360. params.adam_n_iter = 256;
  1361. params.adam_alpha = 1e-3f;
  1362. params.adam_min_alpha = 0;
  1363. params.adam_decay = 1e-1f;
  1364. params.adam_decay_min_ndim = 2;
  1365. params.adam_beta1 = 0.9f;
  1366. params.adam_beta2 = 0.999f;
  1367. params.adam_gclip = 1.0f;
  1368. params.adam_eps_f = 0.0f;
  1369. params.mem_model_gb = 2;
  1370. params.mem_compute_gb = 24;
  1371. params.mem_compute0_gb = 8;
  1372. return params;
  1373. }
  1374. void train_print_usage(int /*argc*/, char ** argv, const struct train_params * params) {
  1375. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  1376. fprintf(stderr, "\n");
  1377. fprintf(stderr, "options:\n");
  1378. fprintf(stderr, " -h, --help show this help message and exit\n");
  1379. fprintf(stderr, " --vocab-model FNAME model path from which to load vocab (default '%s')\n", params->fn_vocab_model);
  1380. fprintf(stderr, " --train-data FNAME path from which to load training data (default '%s')\n", params->fn_train_data);
  1381. fprintf(stderr, " --checkpoint-in FNAME path from which to load training checkpoint (default '%s')\n", params->fn_checkpoint_in);
  1382. fprintf(stderr, " --checkpoint-out FNAME path to save training checkpoint (default '%s')\n", params->fn_checkpoint_out);
  1383. fprintf(stderr, " --model-out FNAME path to save ggml model (default '%s')\n", params->fn_model_out);
  1384. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for -1)\n");
  1385. fprintf(stderr, " -c N, --ctx N Context size used during training (default %d)\n", params->n_ctx);
  1386. fprintf(stderr, " --embd N Embedding size used for new models (default %d)\n", params->n_embd);
  1387. fprintf(stderr, " --ff N Feedforward size used for new models. (default %d)\n", params->n_ff);
  1388. fprintf(stderr, " --head N Number of heads for new models (default %d)\n", params->n_head);
  1389. fprintf(stderr, " --layer N Number of layers for new models (default %d)\n", params->n_layer);
  1390. fprintf(stderr, " --norm-rms-eps F RMS-Norm epsilon value (default %f)\n", params->f_norm_rms_eps);
  1391. fprintf(stderr, " --rope-freq-base F Frequency base for ROPE (default %f)\n", params->rope_freq_base);
  1392. fprintf(stderr, " --rope-freq-scale F Frequency scale for ROPE (default %f)\n", params->rope_freq_scale);
  1393. fprintf(stderr, " -t N, --threads N Number of threads (default %d)\n", params->n_threads);
  1394. fprintf(stderr, " -b N, --batch N Parallel batch size (default %d)\n", params->n_batch);
  1395. fprintf(stderr, " -n N, --examples N Number of examples to train (default %d)\n", params->n_examples);
  1396. fprintf(stderr, " --print-info-interval N Print infos during training each N examples (default %d)\n", params->print_info_interval);
  1397. fprintf(stderr, " --samples-after-nl Training samples start after newlines. (default %s)\n", params->samples_start_after_nl ? "on" : "off");
  1398. fprintf(stderr, " --use-lbfgs Use LBFGS optimizer instead of default Adam\n");
  1399. fprintf(stderr, " --use-adam Use Adam optimizer (default)\n");
  1400. fprintf(stderr, " --no-flash Don't use flash attention \n");
  1401. fprintf(stderr, " --use-flash Use flash attention (default)\n");
  1402. fprintf(stderr, " --no-checkpointing Don't use gradient checkpointing\n");
  1403. fprintf(stderr, " --use-checkpointing Use gradient checkpointing (default)\n");
  1404. fprintf(stderr, " --no-alloc Don't use allocator\n");
  1405. fprintf(stderr, " --use-alloc Use allocator (default)\n");
  1406. fprintf(stderr, " --warmup N Only for Adam optimizer. Number of warmup steps (default %d)\n", params->warmup);
  1407. fprintf(stderr, " --cos-decay-steps N Only for Adam optimizer. Number of cosine decay steps (default %d)\n", params->cos_decay_steps);
  1408. fprintf(stderr, " --cos-decay-restart N Only for Adam optimizer. Increase of cosine decay steps after restart (default %f)\n", params->cos_decay_restart);
  1409. fprintf(stderr, " --cos-decay-min N Only for Adam optimizer. Cosine decay minimum (default %f)\n", params->cos_decay_min);
  1410. fprintf(stderr, " --enable-restart N Only for Adam optimizer. Enable restarts of cos-decay %s\n", params->enable_restart ? "(default)" : "");
  1411. fprintf(stderr, " --disable-restart N Only for Adam optimizer. Disable restarts of cos-decay %s\n", !params->enable_restart ? "(default)" : "");
  1412. fprintf(stderr, " --opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero. (default %d)\n", params->opt_past);
  1413. fprintf(stderr, " --opt-delta N Maximum delta for delta convergence test. Disabled when <= zero. (default %f)\n", params->opt_delta);
  1414. fprintf(stderr, " --opt-max-no-improvement N Maximum number of optimization iterations with no improvement. Disabled when <= zero. (default %d)\n", params->opt_max_no_improvement);
  1415. fprintf(stderr, " --adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero. (default %f)\n", params->adam_eps_f);
  1416. fprintf(stderr, " --adam-iter N Maximum number of Adam optimization iterations for each batch (default %d)\n", params->adam_n_iter);
  1417. fprintf(stderr, " --adam-alpha N Adam learning rate alpha (default %f)\n", params->adam_alpha);
  1418. fprintf(stderr, " --adam-min-alpha N Adam minimum learning rate alpha - including warmup phase (default %f)\n", params->adam_min_alpha);
  1419. fprintf(stderr, " --adam-decay N AdamW weight decay. Values greater zero enable AdamW instead of regular Adam. (default %f)\n", params->adam_decay);
  1420. fprintf(stderr, " --adam-decay-min-ndim N Minimum number of tensor dimensions to apply AdamW weight decay. Weight decay is not applied to tensors with less n_dims. (default %d)\n", params->adam_decay_min_ndim);
  1421. fprintf(stderr, " --adam-beta1 N AdamW beta1 in interval [0,1). How much to smooth the first moment of gradients. (default %f)\n", params->adam_beta1);
  1422. fprintf(stderr, " --adam-beta2 N AdamW beta2 in interval [0,1). How much to smooth the second moment of gradients. (default %f)\n", params->adam_beta2);
  1423. fprintf(stderr, " --adam-gclip N AdamW gradient clipping. Disabled when zero. (default %f)\n", params->adam_gclip);
  1424. fprintf(stderr, " --lbfgs-iter N Maximum number of LBFGS optimization iterations for each batch (default %d)\n", params->lbfgs_n_iter);
  1425. fprintf(stderr, " --mem-model N Memory to allocate for model and cache in gigabytes. (default %d)\n", params->mem_model_gb);
  1426. fprintf(stderr, " --mem-compute N Memory to allocate for compute in gigabytes. (default %d)\n", params->mem_compute_gb);
  1427. fprintf(stderr, " --mem-compute0 N Memory to allocate for automatic memory allocator in gigabytes. (default %d)\n", params->mem_compute0_gb);
  1428. fprintf(stderr, "\n");
  1429. }
  1430. bool train_params_parse(int argc, char ** argv, struct train_params * params) {
  1431. bool invalid_param = false;
  1432. std::string arg;
  1433. struct train_params default_params = get_default_train_params();
  1434. const std::string arg_prefix = "--";
  1435. for (int i = 1; i < argc; i++) {
  1436. arg = argv[i];
  1437. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  1438. std::replace(arg.begin(), arg.end(), '_', '-');
  1439. }
  1440. if (arg == "--vocab-model") {
  1441. if (++i >= argc) {
  1442. invalid_param = true;
  1443. break;
  1444. }
  1445. params->fn_vocab_model = argv[i];
  1446. } else if (arg == "--train-data") {
  1447. if (++i >= argc) {
  1448. invalid_param = true;
  1449. break;
  1450. }
  1451. params->fn_train_data = argv[i];
  1452. } else if (arg == "--checkpoint-in") {
  1453. if (++i >= argc) {
  1454. invalid_param = true;
  1455. break;
  1456. }
  1457. params->fn_checkpoint_in = argv[i];
  1458. } else if (arg == "--checkpoint-out") {
  1459. if (++i >= argc) {
  1460. invalid_param = true;
  1461. break;
  1462. }
  1463. params->fn_checkpoint_out = argv[i];
  1464. } else if (arg == "--model-out") {
  1465. if (++i >= argc) {
  1466. invalid_param = true;
  1467. break;
  1468. }
  1469. params->fn_model_out = argv[i];
  1470. } else if (arg == "-s" || arg == "--seed") {
  1471. if (++i >= argc) {
  1472. invalid_param = true;
  1473. break;
  1474. }
  1475. params->seed = std::stoi(argv[i]);
  1476. } else if (arg == "-c" || arg == "--ctx") {
  1477. if (++i >= argc) {
  1478. invalid_param = true;
  1479. break;
  1480. }
  1481. params->n_ctx = std::stoi(argv[i]);
  1482. } else if (arg == "--embd") {
  1483. if (++i >= argc) {
  1484. invalid_param = true;
  1485. break;
  1486. }
  1487. params->n_embd = std::stoi(argv[i]);
  1488. } else if (arg == "--ff") {
  1489. if (++i >= argc) {
  1490. invalid_param = true;
  1491. break;
  1492. }
  1493. params->n_ff = std::stoi(argv[i]);
  1494. } else if (arg == "--head") {
  1495. if (++i >= argc) {
  1496. invalid_param = true;
  1497. break;
  1498. }
  1499. params->n_head = std::stoi(argv[i]);
  1500. } else if (arg == "--layer") {
  1501. if (++i >= argc) {
  1502. invalid_param = true;
  1503. break;
  1504. }
  1505. params->n_layer = std::stoi(argv[i]);
  1506. } else if (arg == "--norm-rms-eps") {
  1507. if (++i >= argc) {
  1508. invalid_param = true;
  1509. break;
  1510. }
  1511. params->f_norm_rms_eps = std::stof(argv[i]);
  1512. } else if (arg == "--rope-freq-base") {
  1513. if (++i >= argc) {
  1514. invalid_param = true;
  1515. break;
  1516. }
  1517. params->rope_freq_base = std::stof(argv[i]);
  1518. } else if (arg == "--rope-freq-scale") {
  1519. if (++i >= argc) {
  1520. invalid_param = true;
  1521. break;
  1522. }
  1523. params->rope_freq_scale = std::stof(argv[i]);
  1524. } else if (arg == "-t" || arg == "--threads") {
  1525. if (++i >= argc) {
  1526. invalid_param = true;
  1527. break;
  1528. }
  1529. params->n_threads = std::stoi(argv[i]);
  1530. } else if (arg == "-b" || arg == "--batch") {
  1531. if (++i >= argc) {
  1532. invalid_param = true;
  1533. break;
  1534. }
  1535. params->n_batch = std::stoi(argv[i]);
  1536. } else if (arg == "-n" || arg == "--examples") {
  1537. if (++i >= argc) {
  1538. invalid_param = true;
  1539. break;
  1540. }
  1541. params->n_examples = std::stoi(argv[i]);
  1542. } else if (arg == "--print-info-interval") {
  1543. if (++i >= argc) {
  1544. invalid_param = true;
  1545. break;
  1546. }
  1547. params->print_info_interval = std::stoi(argv[i]);
  1548. } else if (arg == "--samples-after-nl") {
  1549. params->samples_start_after_nl = true;
  1550. } else if (arg == "--use-lbfgs") {
  1551. params->use_adam = false;
  1552. } else if (arg == "--use-adam") {
  1553. params->use_adam = true;
  1554. } else if (arg == "--no-flash") {
  1555. params->use_flash = false;
  1556. } else if (arg == "--use-flash") {
  1557. params->use_flash = true;
  1558. } else if (arg == "--no-checkpointing") {
  1559. params->use_checkpointing = false;
  1560. } else if (arg == "--use-checkpointing") {
  1561. params->use_checkpointing = true;
  1562. } else if (arg == "--no-alloc") {
  1563. params->use_alloc = false;
  1564. } else if (arg == "--use-alloc") {
  1565. params->use_alloc = true;
  1566. } else if (arg == "--warmup") {
  1567. if (++i >= argc) {
  1568. invalid_param = true;
  1569. break;
  1570. }
  1571. params->warmup = std::stoi(argv[i]);
  1572. } else if (arg == "--cos-decay-steps") {
  1573. if (++i >= argc) {
  1574. invalid_param = true;
  1575. break;
  1576. }
  1577. params->cos_decay_steps = std::stof(argv[i]);
  1578. } else if (arg == "--cos-decay-restart") {
  1579. if (++i >= argc) {
  1580. invalid_param = true;
  1581. break;
  1582. }
  1583. params->cos_decay_restart = std::stof(argv[i]);
  1584. } else if (arg == "--cos-decay-min") {
  1585. if (++i >= argc) {
  1586. invalid_param = true;
  1587. break;
  1588. }
  1589. params->cos_decay_min = std::stof(argv[i]);
  1590. } else if (arg == "--enable-restart") {
  1591. params->enable_restart = true;
  1592. } else if (arg == "--disable-restart") {
  1593. params->enable_restart = false;
  1594. } else if (arg == "--opt-past") {
  1595. if (++i >= argc) {
  1596. invalid_param = true;
  1597. break;
  1598. }
  1599. params->opt_past = std::stoi(argv[i]);
  1600. } else if (arg == "--opt-delta") {
  1601. if (++i >= argc) {
  1602. invalid_param = true;
  1603. break;
  1604. }
  1605. params->opt_delta = std::stof(argv[i]);
  1606. } else if (arg == "--opt-max-no-improvement") {
  1607. if (++i >= argc) {
  1608. invalid_param = true;
  1609. break;
  1610. }
  1611. params->opt_max_no_improvement = std::stoi(argv[i]);
  1612. } else if (arg == "--adam-epsf") {
  1613. if (++i >= argc) {
  1614. invalid_param = true;
  1615. break;
  1616. }
  1617. params->adam_eps_f = std::stof(argv[i]);
  1618. } else if (arg == "--adam-iter") {
  1619. if (++i >= argc) {
  1620. invalid_param = true;
  1621. break;
  1622. }
  1623. params->adam_n_iter = std::stoi(argv[i]);
  1624. } else if (arg == "--adam-alpha") {
  1625. if (++i >= argc) {
  1626. invalid_param = true;
  1627. break;
  1628. }
  1629. params->adam_alpha = std::stof(argv[i]);
  1630. } else if (arg == "--adam-min-alpha") {
  1631. if (++i >= argc) {
  1632. invalid_param = true;
  1633. break;
  1634. }
  1635. params->adam_min_alpha = std::stof(argv[i]);
  1636. } else if (arg == "--adam-decay") {
  1637. if (++i >= argc) {
  1638. invalid_param = true;
  1639. break;
  1640. }
  1641. params->adam_decay = std::stof(argv[i]);
  1642. } else if (arg == "--adam-decay-min-ndim") {
  1643. if (++i >= argc) {
  1644. invalid_param = true;
  1645. break;
  1646. }
  1647. params->adam_decay_min_ndim = std::stoi(argv[i]);
  1648. } else if (arg == "--adam-beta1") {
  1649. if (++i >= argc) {
  1650. invalid_param = true;
  1651. break;
  1652. }
  1653. params->adam_beta1 = std::stof(argv[i]);
  1654. } else if (arg == "--adam-beta2") {
  1655. if (++i >= argc) {
  1656. invalid_param = true;
  1657. break;
  1658. }
  1659. params->adam_beta2 = std::stof(argv[i]);
  1660. } else if (arg == "--adam-gclip") {
  1661. if (++i >= argc) {
  1662. invalid_param = true;
  1663. break;
  1664. }
  1665. params->adam_gclip = std::stof(argv[i]);
  1666. } else if (arg == "--lbfgs-iter") {
  1667. if (++i >= argc) {
  1668. invalid_param = true;
  1669. break;
  1670. }
  1671. params->lbfgs_n_iter = std::stoi(argv[i]);
  1672. } else if (arg == "--mem-model") {
  1673. if (++i >= argc) {
  1674. invalid_param = true;
  1675. break;
  1676. }
  1677. params->mem_model_gb = std::stoi(argv[i]);
  1678. } else if (arg == "--mem-compute") {
  1679. if (++i >= argc) {
  1680. invalid_param = true;
  1681. break;
  1682. }
  1683. params->mem_compute_gb = std::stoi(argv[i]);
  1684. } else if (arg == "--mem-compute0") {
  1685. if (++i >= argc) {
  1686. invalid_param = true;
  1687. break;
  1688. }
  1689. params->mem_compute0_gb = std::stoi(argv[i]);
  1690. } else if (arg == "-h" || arg == "--help") {
  1691. train_print_usage(argc, argv, &default_params);
  1692. exit(0);
  1693. } else {
  1694. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  1695. train_print_usage(argc, argv, &default_params);
  1696. exit(1);
  1697. }
  1698. }
  1699. if (invalid_param) {
  1700. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  1701. train_print_usage(argc, argv, &default_params);
  1702. exit(1);
  1703. }
  1704. return true;
  1705. }
  1706. struct opt_callback_data {
  1707. struct train_params * params;
  1708. struct ggml_opt_context * opt;
  1709. struct llama_context * lctx;
  1710. llama_token * tokens_data;
  1711. size_t tokens_size;
  1712. int * samples_data;
  1713. size_t samples_size;
  1714. int shuffle_countdown;
  1715. struct ggml_tensor * tokens_input;
  1716. struct ggml_tensor * target_logits;
  1717. struct ggml_tensor * target_probs;
  1718. };
  1719. void opt_callback(void * vdata, float * sched) {
  1720. struct opt_callback_data * data = (struct opt_callback_data *) vdata;
  1721. struct train_params * params = data->params;
  1722. struct ggml_opt_context * opt = data->opt;
  1723. int n_batch = params->n_batch;
  1724. *sched = (opt->iter < params->warmup)
  1725. ? (float) opt->iter / (float) params->warmup
  1726. : cosine_decay_restart(
  1727. params->cos_decay_steps,
  1728. params->cos_decay_min,
  1729. opt->iter - params->warmup,
  1730. params->cos_decay_restart,
  1731. params->enable_restart);
  1732. float min_sched = params->adam_min_alpha / params->adam_alpha;
  1733. *sched = min_sched + *sched * (1.0f - min_sched);
  1734. int impr_plot = std::isnan(opt->loss_after) ? 0 : -(int)(1 + (opt->loss_before - opt->loss_after) * 10.0f + 0.5f);
  1735. printf("%s: iter=%*d, sched=%f loss0=%f loss=%f | improvement: %*d>\n", __func__, 6, opt->iter, *sched, opt->loss_before, opt->loss_after, impr_plot, (int)0);
  1736. if (data->shuffle_countdown < n_batch) {
  1737. printf("%s: reshuffle samples\n", __func__);
  1738. shuffle_ints(data->samples_data, data->samples_data + data->samples_size);
  1739. for (int i = 0; i < (int) data->samples_size; ++i) {
  1740. GGML_ASSERT(data->samples_data[i]+params->n_ctx-1 < (int) data->tokens_size);
  1741. }
  1742. data->shuffle_countdown = data->samples_size;
  1743. }
  1744. get_example_targets_batch(
  1745. data->lctx,
  1746. data->samples_data,
  1747. data->samples_size,
  1748. data->tokens_data,
  1749. data->tokens_size,
  1750. opt->iter,
  1751. data->tokens_input,
  1752. data->target_logits,
  1753. data->target_probs);
  1754. data->shuffle_countdown -= n_batch;
  1755. }
  1756. int main(int argc, char ** argv) {
  1757. struct train_params params = get_default_train_params();
  1758. if (!train_params_parse(argc, argv, &params)) {
  1759. return 1;
  1760. }
  1761. if (params.seed == LLAMA_DEFAULT_SEED) {
  1762. params.seed = time(NULL);
  1763. }
  1764. printf("%s: seed: %u\n", __func__, params.seed);
  1765. srand(params.seed);
  1766. struct llama_context_params llama_params = llama_context_default_params();
  1767. llama_params.vocab_only = true;
  1768. struct llama_model * lmodel = llama_load_model_from_file(params.fn_vocab_model, llama_params);
  1769. struct llama_context * lctx = llama_new_context_with_model(lmodel, llama_params);
  1770. printf("%s: tokenize training data\n", __func__);
  1771. std::vector<llama_token> train_tokens;
  1772. if (tokenize_file(lctx, params.fn_train_data, train_tokens) < 0) {
  1773. fprintf(stderr, "%s: failed to tokenize file '%s'\n", __func__, params.fn_train_data);
  1774. }
  1775. printf("%s: number of training tokens: %d\n", __func__, (int) train_tokens.size());
  1776. struct my_llama_model model;
  1777. model.hparams.n_vocab = llama_n_vocab(lctx);
  1778. model.hparams.n_ctx = params.n_ctx;
  1779. model.hparams.n_embd = params.n_embd;
  1780. model.hparams.n_head = params.n_head;
  1781. model.hparams.n_layer = params.n_layer;
  1782. model.hparams.n_ff = params.n_ff;
  1783. // llama.cpp requires n_rot to be exactly n_embd / n_head
  1784. model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  1785. model.hparams.f_norm_rms_eps = params.f_norm_rms_eps;
  1786. model.hparams.rope_freq_base = params.rope_freq_base;
  1787. model.hparams.rope_freq_scale = params.rope_freq_scale;
  1788. print_params(&model.hparams);
  1789. std::vector<size_t> token_noccurs;
  1790. std::vector<bool> token_notavail;
  1791. token_noccurs.resize(model.hparams.n_vocab, 0);
  1792. token_notavail.resize(model.hparams.n_vocab, true);
  1793. for (int i = 0; i < (int) train_tokens.size(); ++i) {
  1794. ++token_noccurs[train_tokens[i]];
  1795. token_notavail[train_tokens[i]] = false;
  1796. }
  1797. std::vector<float> token_freq;
  1798. token_freq.resize(model.hparams.n_vocab, 0);
  1799. int n_unique_tokens = 0;
  1800. for (int i = 0; i < (int) token_noccurs.size(); ++i) {
  1801. token_freq[i] = (float) token_noccurs[i] / (float) train_tokens.size();
  1802. n_unique_tokens += (token_noccurs[i] > 0) ? 1 : 0;
  1803. }
  1804. printf("%s: number of unique tokens: %d\n", __func__, n_unique_tokens);
  1805. struct ggml_init_params lcparams;
  1806. lcparams.mem_size = 1024ll*1024ll*1024ll*((size_t) params.mem_model_gb);
  1807. lcparams.mem_buffer = NULL;
  1808. lcparams.no_alloc = false;
  1809. model.ctx = ggml_init(lcparams);
  1810. int n_tokens = model.hparams.n_ctx;
  1811. int n_vocab = model.hparams.n_vocab;
  1812. int n_batch = params.n_batch;
  1813. struct ggml_opt_context * opt = (struct ggml_opt_context *) alloca(sizeof(struct ggml_opt_context));
  1814. memset(opt, 0, sizeof(struct ggml_opt_context));
  1815. struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
  1816. struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
  1817. opt_params_adam.print_forward_graph = false;
  1818. opt_params_adam.print_backward_graph = false;
  1819. opt_params_adam.n_threads = params.n_threads;
  1820. opt_params_adam.past = params.opt_past;
  1821. opt_params_adam.delta = params.opt_delta;
  1822. opt_params_adam.max_no_improvement = params.opt_max_no_improvement;
  1823. opt_params_adam.adam.n_iter = params.adam_n_iter;
  1824. opt_params_adam.adam.sched = 1.0f;
  1825. opt_params_adam.adam.alpha = params.adam_alpha;
  1826. opt_params_adam.adam.decay = params.adam_decay;
  1827. opt_params_adam.adam.decay_min_ndim = params.adam_decay_min_ndim;
  1828. opt_params_adam.adam.beta1 = params.adam_beta1;
  1829. opt_params_adam.adam.beta2 = params.adam_beta2;
  1830. opt_params_adam.adam.gclip = params.adam_gclip;
  1831. opt_params_adam.adam.eps_f = params.adam_eps_f;
  1832. opt_params_lbfgs.print_forward_graph = false;
  1833. opt_params_lbfgs.print_backward_graph = false;
  1834. opt_params_lbfgs.n_threads = params.n_threads;
  1835. opt_params_adam.past = params.opt_past;
  1836. opt_params_adam.delta = params.opt_delta;
  1837. opt_params_adam.max_no_improvement = params.opt_max_no_improvement;
  1838. opt_params_lbfgs.lbfgs.n_iter = params.lbfgs_n_iter;
  1839. opt->ctx = model.ctx;
  1840. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  1841. printf("%s: init model\n", __func__);
  1842. bool existed = load_checkpoint_file(params.fn_checkpoint_in, &model, opt);
  1843. if (!existed) {
  1844. init_model(&model);
  1845. }
  1846. set_param_model(&model);
  1847. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  1848. opt->iter = model.train_its;
  1849. printf("%s: opt iter %d\n", __func__, opt->iter);
  1850. bool from_scratch = !existed;
  1851. if (from_scratch) {
  1852. randomize_model(&model, params.seed, 0.0f, 1.0f, -1.0f, +1.0f);
  1853. }
  1854. printf("used_mem model: %zu bytes\n", ggml_used_mem(model.ctx));
  1855. // ggml_print_tensor_objects(model.ctx);
  1856. // TODO: use std::vector<uint8_t> intead of "new"
  1857. size_t compute_size = 1024ll*1024ll*1024ll*((size_t) params.mem_compute_gb);
  1858. uint8_t * compute_addr = new uint8_t[compute_size];
  1859. size_t size_buf_0 = 1024ll*1024ll*1024ll*((size_t) params.mem_compute0_gb);
  1860. uint8_t * compute_buf_0 = new uint8_t[size_buf_0];
  1861. ggml_allocr * alloc = NULL;
  1862. if (params.use_alloc) {
  1863. static const size_t tensor_alignment = 32;
  1864. alloc = ggml_allocr_new(compute_buf_0, size_buf_0, tensor_alignment);
  1865. }
  1866. GGML_ASSERT(n_tokens < (int) train_tokens.size());
  1867. std::vector<int> train_samples;
  1868. train_samples.push_back(0);
  1869. for (int i = 1; i < (int) train_tokens.size() - n_tokens; ++i) {
  1870. if (!params.samples_start_after_nl || (train_tokens[i-1] == llama_token_nl(lctx))) {
  1871. train_samples.push_back(i);
  1872. }
  1873. }
  1874. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  1875. for (int i = 0; i < (int) train_samples.size(); ++i) {
  1876. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  1877. }
  1878. printf("%s: begin training\n", __func__);
  1879. struct opt_callback_data opt_cb_data;
  1880. opt_cb_data.params = &params;
  1881. opt_cb_data.opt = opt;
  1882. opt_cb_data.lctx = lctx;
  1883. opt_cb_data.tokens_data = train_tokens.data();
  1884. opt_cb_data.tokens_size = train_tokens.size();
  1885. opt_cb_data.samples_data = train_samples.data();
  1886. opt_cb_data.samples_size = train_samples.size();
  1887. opt_cb_data.shuffle_countdown = train_samples.size();
  1888. opt_cb_data.tokens_input = NULL;
  1889. opt_cb_data.target_logits = NULL;
  1890. opt_cb_data.target_probs = NULL;
  1891. int64_t t0 = ggml_time_ms();
  1892. for (int ex = 0; ex < params.n_examples; ++ex) {
  1893. if (ex*n_batch >= (int) train_samples.size()) {
  1894. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  1895. for (int i = 0; i < (int) train_samples.size(); ++i) {
  1896. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  1897. }
  1898. }
  1899. struct ggml_init_params cparams = {
  1900. compute_size, // mem_size
  1901. compute_addr, // mem_buffer
  1902. false, // no_alloc
  1903. };
  1904. struct ggml_context * ctx0 = ggml_init(cparams);
  1905. ggml_set_no_alloc(ctx0, false);
  1906. // don't use alloc for input tensors, so we can safely fill them with data
  1907. //struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1908. //struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1909. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1910. struct ggml_tensor * target_logits = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1911. struct ggml_tensor * target_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1912. ggml_set_no_alloc(ctx0, (alloc != NULL));
  1913. if (alloc) {
  1914. ggml_allocr_reset(alloc);
  1915. }
  1916. opt_cb_data.tokens_input = tokens_input;
  1917. opt_cb_data.target_logits = target_logits;
  1918. opt_cb_data.target_probs = target_probs;
  1919. int n_past = 0;
  1920. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  1921. struct ggml_cgraph * gb = ggml_new_graph(ctx0);
  1922. struct ggml_cgraph * gb_tmp = params.use_checkpointing
  1923. ? ggml_new_graph(ctx0)
  1924. : NULL;
  1925. GGML_ASSERT(n_past == 0);
  1926. struct ggml_tensor * loss = NULL;
  1927. struct ggml_tensor * logits = NULL;
  1928. loss = llama_build_train_graphs(
  1929. &model, alloc, ctx0,
  1930. gf, gb, gb_tmp,
  1931. &logits, tokens_input, target_probs,
  1932. n_tokens, n_batch,
  1933. params.use_flash,
  1934. params.use_checkpointing
  1935. );
  1936. size_t used_mem_before_opt = ggml_used_mem(ctx0);
  1937. opt->params.adam.sched = (opt->iter < params.warmup)
  1938. ? (float) opt->iter / (float) params.warmup
  1939. : cosine_decay_restart(
  1940. params.cos_decay_steps,
  1941. params.cos_decay_min,
  1942. opt->iter - params.warmup,
  1943. params.cos_decay_restart,
  1944. params.enable_restart);
  1945. float min_sched = params.adam_min_alpha / params.adam_alpha;
  1946. opt->params.adam.sched = min_sched + opt->params.adam.sched * (1.0f - min_sched);
  1947. printf("%s: opt->params.adam.sched %.5f\n", __func__, opt->params.adam.sched);
  1948. ggml_opt_resume_g(ctx0, opt, loss, gf, gb, &opt_callback, (void *) &opt_cb_data);
  1949. size_t used_mem_after_opt = ggml_used_mem(ctx0);
  1950. int n_iter = params.use_adam ? params.adam_n_iter : params.lbfgs_n_iter;
  1951. model.train_its = opt->iter;
  1952. model.train_samples += n_batch * n_iter;
  1953. model.train_tokens += n_batch * n_tokens * n_iter;
  1954. if (params.print_info_interval > 0 && ex % params.print_info_interval == 0) {
  1955. printf("Example %d, opt iter %d\n", ex, opt->iter);
  1956. printf("error_before_opt: %.6f\n", opt->loss_before);
  1957. printf("error_after_opt: %.6f\n", opt->loss_after);
  1958. printf("used_mem_before_opt: %zu bytes\n", used_mem_before_opt);
  1959. printf("used_mem_after_opt: %zu bytes\n", used_mem_after_opt);
  1960. }
  1961. ggml_free(ctx0);
  1962. }
  1963. int64_t t1 = ggml_time_ms();
  1964. int64_t d = t1-t0;
  1965. double dd = (double) d * 1e-3;
  1966. printf("%s: total training time=%f seconds\n", __func__, dd);
  1967. if (params.n_examples > 0) {
  1968. save_checkpoint_file(params.fn_checkpoint_out, params.fn_vocab_model, &model, opt);
  1969. }
  1970. if (strlen(params.fn_model_out) > 0) {
  1971. save_llama_model_file(params.fn_model_out, params.fn_vocab_model, &model);
  1972. }
  1973. if (alloc) {
  1974. ggml_allocr_free(alloc);
  1975. }
  1976. delete[] compute_addr;
  1977. delete[] compute_buf_0;
  1978. ggml_free(model.ctx);
  1979. llama_free(lctx);
  1980. llama_free_model(lmodel);
  1981. return 0;
  1982. }