train-text-from-scratch.cpp 97 KB

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