train-text-from-scratch.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281
  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. // KQ_pos - contains the positions
  578. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
  579. {
  580. int * data = (int *) KQ_pos->data;
  581. for (int i = 0; i < N; ++i) {
  582. data[i] = n_past + i;
  583. }
  584. }
  585. // rope has so much parameters that we make a custom function for it
  586. auto rope = [ctx, KQ_pos, n_rot, n_ctx, rope_freq_base, rope_freq_scale]
  587. (struct ggml_tensor * t) -> struct ggml_tensor * {
  588. // not capturing these, to silcence warnings
  589. const int rope_mode = 0;
  590. return ggml_rope_custom(ctx,
  591. t, KQ_pos, n_rot, rope_mode, n_ctx,
  592. rope_freq_base, rope_freq_scale);
  593. };
  594. set_name(tokens_input, "tokens_input");
  595. set_name(targets, "targets");
  596. GGML_ASSERT(tokens_input->type == GGML_TYPE_I32);
  597. struct ggml_tensor * t00 = ggml_reshape_1d(ctx, tokens_input, N*n_batch); set_name(t00, "t00"); assert_shape_1d(t00, N*n_batch);
  598. 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);
  599. struct ggml_tensor * cur = t01;
  600. std::vector<struct ggml_tensor *> checkpoints;
  601. checkpoints.push_back(tokens_input);
  602. checkpoints.push_back(targets);
  603. checkpoints.push_back(t00);
  604. checkpoints.push_back(t01);
  605. struct ggml_tensor * kv_scale;
  606. if (!enable_flash_attn) {
  607. kv_scale = ggml_new_f32(ctx, 1.0f/sqrtf(float(n_embd)/n_head));
  608. }
  609. for (int il = 0; il < n_layer; ++il) {
  610. struct my_llama_layer & layer = model->layers[il];
  611. 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);
  612. struct ggml_tensor * t03 = ggml_repeat (ctx, layer.attention_norm, t02); set_name(t03, "t03"); assert_shape_2d(t03, n_embd, N*n_batch);
  613. struct ggml_tensor * t04 = ggml_mul (ctx, t03, t02); set_name(t04, "t04"); assert_shape_2d(t04, n_embd, N*n_batch);
  614. struct ggml_tensor * t05 = ggml_mul_mat (ctx, layer.wq, t04); set_name(t05, "t05"); assert_shape_2d(t05, n_embd, N*n_batch);
  615. 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);
  616. struct ggml_tensor * t07 = rope (t06); set_name(t07, "t07"); assert_shape_4d(t07, n_embd/n_head, n_head, N, n_batch);
  617. struct ggml_tensor * t08 = ggml_mul_mat (ctx, layer.wk, t04); set_name(t08, "t08"); assert_shape_2d(t08, n_embd, N*n_batch);
  618. 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);
  619. struct ggml_tensor * t10 = rope (t09); set_name(t10, "t10"); assert_shape_4d(t10, n_embd/n_head, n_head, N, n_batch);
  620. struct ggml_tensor * t11 = ggml_mul_mat (ctx, t04, layer.wv); set_name(t11, "t11"); assert_shape_2d(t11, N*n_batch, n_embd);
  621. 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);
  622. 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);
  623. 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);
  624. 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);
  625. struct ggml_tensor * t16;
  626. if (enable_flash_attn) {
  627. 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);
  628. } else {
  629. 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);
  630. 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);
  631. 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);
  632. 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);
  633. 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);
  634. }
  635. 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);
  636. 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);
  637. 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);
  638. struct ggml_tensor * t20 = ggml_mul_mat (ctx, layer.wo, t19); set_name(t20, "t20"); assert_shape_2d(t20, n_embd, N*n_batch);
  639. struct ggml_tensor * t21 = ggml_add (ctx, t20, cur); set_name(t21, "t21"); assert_shape_2d(t21, n_embd, N*n_batch);
  640. 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);
  641. struct ggml_tensor * t23 = ggml_repeat (ctx, layer.ffn_norm, t22); set_name(t23, "t23"); assert_shape_2d(t23, n_embd, N*n_batch);
  642. struct ggml_tensor * t24 = ggml_mul (ctx, t23, t22); set_name(t24, "t24"); assert_shape_2d(t24, n_embd, N*n_batch);
  643. struct ggml_tensor * t25 = ggml_mul_mat (ctx, layer.w3, t24); set_name(t25, "t25"); assert_shape_2d(t25, n_ff, N*n_batch);
  644. struct ggml_tensor * t26 = ggml_mul_mat (ctx, layer.w1, t24); set_name(t26, "t26"); assert_shape_2d(t26, n_ff, N*n_batch);
  645. struct ggml_tensor * t27 = ggml_silu (ctx, t26); set_name(t27, "t27"); assert_shape_2d(t27, n_ff, N*n_batch);
  646. struct ggml_tensor * t28 = ggml_mul (ctx, t27, t25); set_name(t28, "t28"); assert_shape_2d(t28, n_ff, N*n_batch);
  647. struct ggml_tensor * t29 = ggml_mul_mat (ctx, layer.w2, t28); set_name(t29, "t29"); assert_shape_2d(t29, n_embd, N*n_batch);
  648. struct ggml_tensor * t30 = ggml_add (ctx, t29, t21); set_name(t30, "t30"); assert_shape_2d(t30, n_embd, N*n_batch);
  649. cur = t30;
  650. checkpoints.push_back(cur);
  651. }
  652. 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);
  653. struct ggml_tensor * t32 = ggml_repeat (ctx, model->norm, t31); set_name(t32, "t32"); assert_shape_2d(t32, n_embd, N*n_batch);
  654. struct ggml_tensor * t33 = ggml_mul (ctx, t32, t31); set_name(t33, "t33"); assert_shape_2d(t33, n_embd, N*n_batch);
  655. struct ggml_tensor * t34 = ggml_mul_mat (ctx, model->output, t33); set_name(t34, "t34"); assert_shape_2d(t34, n_vocab, N*n_batch);
  656. 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);
  657. struct ggml_tensor * t36 = ggml_cross_entropy_loss(ctx, t35, targets); set_name(t36, "t36"); assert_shape_1d(t36, 1);
  658. checkpoints.push_back(t31);
  659. checkpoints.push_back(t32);
  660. checkpoints.push_back(t33);
  661. checkpoints.push_back(t34);
  662. checkpoints.push_back(t35);
  663. checkpoints.push_back(t36);
  664. ggml_build_forward_expand(gf, t36);
  665. if (enable_checkpointing) {
  666. ggml_build_backward_gradient_checkpointing(ctx, gf, gb, gb_tmp, checkpoints.data(), (int) checkpoints.size());
  667. } else {
  668. *gb = *gf;
  669. ggml_build_backward_expand(ctx, gf, gb, true);
  670. }
  671. if (alloc) {
  672. // make sure some tensors are not reallocated by inserting new temporary nodes depending on them
  673. int n_leafs_before = gb->n_leafs;
  674. int n_nodes_before = gb->n_nodes;
  675. struct ggml_tensor * one = ggml_new_f32(ctx, 1.0f);
  676. // output tensors
  677. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t35, one));
  678. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36, one));
  679. // input gradient
  680. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36->grad, one));
  681. // KQ_pos
  682. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, KQ_pos, one));
  683. GGML_ASSERT(t36->grad->data == NULL && !ggml_is_view(t36->grad));
  684. ggml_allocr_alloc(alloc, t36->grad);
  685. // gradient tensors (will be set to zero by ggml_graph_reset)
  686. // pinning these produces large unnecessary memory overhead, which will be resolved by PR 2632
  687. for (int i = 0; i < gf->n_nodes; ++i) {
  688. if (!gf->grads[i]) continue;
  689. if (gf->grads[i]->data == NULL && !ggml_is_view(gf->grads[i])) {
  690. ggml_allocr_alloc(alloc, gf->grads[i]);
  691. }
  692. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, gf->grads[i], one));
  693. }
  694. // allocating checkpoints in one block to reduce memory fragmentation
  695. // note: they will be freed in reverse order
  696. for (int i = 0; i < (int) checkpoints.size(); ++i) {
  697. if (checkpoints[i]->data == NULL && !ggml_is_view(checkpoints[i])) {
  698. ggml_allocr_alloc(alloc, checkpoints[i]);
  699. }
  700. }
  701. //int n_leafs_after = gb->n_leafs;
  702. //int n_nodes_after = gb->n_nodes;
  703. ggml_allocr_alloc_graph(alloc, gb);
  704. // remove the additional nodes and leafs
  705. for (int i = n_leafs_before; i < gb->n_leafs; ++i) {
  706. gb->leafs[i] = NULL;
  707. }
  708. for (int i = n_nodes_before; i < gb->n_nodes; ++i) {
  709. gb->nodes[i] = NULL;
  710. }
  711. gb->n_leafs = n_leafs_before;
  712. gb->n_nodes = n_nodes_before;
  713. }
  714. *logits = t35;
  715. return t36;
  716. }
  717. void set_f32_3d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int64_t i2, float value) {
  718. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  719. *ptr = value;
  720. }
  721. void set_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, float value) {
  722. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  723. *ptr = value;
  724. }
  725. void set_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1, int32_t value) {
  726. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  727. *ptr = value;
  728. }
  729. float get_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  730. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  731. return *ptr;
  732. }
  733. int32_t get_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  734. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  735. return *ptr;
  736. }
  737. void print_row(struct ggml_tensor * probs, int 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. void print_matrix(struct ggml_tensor * probs) {
  745. assert(probs->n_dims == 2);
  746. for (int i = 0; i < probs->ne[1]; ++i) {
  747. for (int k = 0; k < probs->ne[0]; ++k) {
  748. float p = get_f32_2d(probs, k, i);
  749. printf(" %.2f", p);
  750. }
  751. printf("\n");
  752. }
  753. }
  754. 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) {
  755. int n_tokens = tokens_input->ne[0];
  756. int n_vocab = target_logits->ne[0];
  757. size_t sample = train_samples[example_id % n_train_samples];
  758. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  759. ggml_set_f32(target_logits, -1.0f/n_vocab);
  760. ggml_set_f32(target_probs, 0.0f);
  761. ggml_set_i32_1d(tokens_input, 0, llama_token_bos(lctx));
  762. for (int i=1; i<n_tokens+1; ++i) {
  763. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  764. set_f32_2d(target_logits, token, i-1, +1.0f);
  765. set_f32_2d(target_probs, token, i-1, +1.0f);
  766. if (i<n_tokens) {
  767. ggml_set_i32_1d(tokens_input, i, token);
  768. }
  769. }
  770. }
  771. 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) {
  772. GGML_ASSERT(tokens_input->n_dims == 2);
  773. GGML_ASSERT(target_logits->n_dims == 3);
  774. GGML_ASSERT(target_probs->n_dims == 3);
  775. int n_vocab = target_logits->ne[0];
  776. int n_tokens = tokens_input->ne[0];
  777. int n_batch = tokens_input->ne[1];
  778. GGML_ASSERT(n_tokens == target_logits->ne[1]);
  779. GGML_ASSERT(n_batch == target_logits->ne[2]);
  780. GGML_ASSERT(n_vocab == target_probs->ne[0]);
  781. GGML_ASSERT(n_tokens == target_probs->ne[1]);
  782. GGML_ASSERT(n_batch == target_probs->ne[2]);
  783. ggml_set_f32(target_logits, -1.0f/n_vocab);
  784. ggml_set_f32(target_probs, 0.0f);
  785. // printf("%s: example_id=%d n_batch=%d n_train_samples=%zu\n", __func__, example_id, n_batch, n_train_samples);
  786. for (int k=0; k<n_batch; ++k) {
  787. // printf("%s: batch %d\n", __func__, k);
  788. size_t sample_idx = (example_id*n_batch + k) % n_train_samples;
  789. size_t sample = train_samples[sample_idx];
  790. // printf("%s: sample_idx=%zu sample=%zu\n", __func__, sample_idx, sample);
  791. GGML_ASSERT(sample+n_tokens-1 < n_train_data);
  792. set_i32_2d(tokens_input, 0, k, llama_token_bos(lctx));
  793. for (int i=1; i<n_tokens+1; ++i) {
  794. int token = clamp(train_data[sample+i-1], 0, n_vocab-1);
  795. set_f32_3d(target_logits, token, i-1, k, +1.0f);
  796. set_f32_3d(target_probs, token, i-1, k, +1.0f);
  797. if (i<n_tokens) {
  798. set_i32_2d(tokens_input, i, k, token);
  799. }
  800. }
  801. }
  802. }
  803. int tokenize_file(struct llama_context * lctx, const char * filename, std::vector<llama_token>& out) {
  804. FILE * fp = std::fopen(filename, "rb");
  805. if (fp == NULL) {
  806. return 0;
  807. }
  808. #ifdef _WIN32
  809. GGML_ASSERT(_fseeki64(fp, (__int64) 0, SEEK_END) == 0);
  810. #else
  811. GGML_ASSERT(std::fseek(fp, (long) 0, SEEK_END) == 0);
  812. #endif
  813. size_t size = 0;
  814. #ifdef _WIN32
  815. __int64 ret = _ftelli64(fp);
  816. size = ret;
  817. #else
  818. long ret = std::ftell(fp);
  819. size = ret;
  820. #endif
  821. #ifdef _WIN32
  822. GGML_ASSERT(_fseeki64(fp, (__int64) 0, SEEK_SET) == 0);
  823. #else
  824. GGML_ASSERT(std::fseek(fp, (long) 0, SEEK_SET) == 0);
  825. #endif
  826. std::vector<char> buf;
  827. buf.resize(size+1);
  828. out.resize(size+1);
  829. if (std::fread(buf.data(), size, 1, fp) != 1) {
  830. die("unexpectedly reached end of file");
  831. }
  832. if (ferror(fp)) {
  833. die_fmt("fread failed: %s", strerror(errno));
  834. }
  835. buf[size] = '\0';
  836. int n_tokens = llama_tokenize(lctx, buf.data(), buf.size(), out.data(), out.size(), false);
  837. if (n_tokens < 0) {
  838. out.resize(-n_tokens);
  839. n_tokens = llama_tokenize(lctx, buf.data(), buf.size(), out.data(), out.size(), false);
  840. }
  841. GGML_ASSERT(n_tokens >= 0);
  842. out.resize(n_tokens);
  843. bool verify = false;
  844. if (verify) {
  845. const char * in = buf.data();
  846. const char * end = buf.data() + buf.size();
  847. for (int i = 0; i < (int) out.size(); ++i) {
  848. std::string s = llama_token_to_piece(lctx, out[i]);
  849. int len = s.length();
  850. if (in >= end) {
  851. printf("%s: unexpected end of original text.\n", __func__);
  852. break;
  853. }
  854. const bool matches = (strncmp(in, s.c_str(), len) == 0);
  855. if (matches) {
  856. in += len;
  857. } else {
  858. printf("%s: mismatch: expected '%s', but got '%s'\n", __func__, std::string(in, len).c_str(), s.c_str());
  859. }
  860. }
  861. }
  862. return n_tokens;
  863. }
  864. void shuffle_ints(int * begin, int * end) {
  865. if (end <= begin) return;
  866. int max=begin[0];
  867. for (int i=1; i<end-begin; ++i) {
  868. if (begin[i] > max) {
  869. max = begin[i];
  870. }
  871. }
  872. std::vector<float> vals;
  873. vals.resize(max+1);
  874. for (int i=0; i<max+1; ++i) {
  875. vals[i] = frand();
  876. }
  877. std::sort(begin, end, [&vals](int a, int b){
  878. return vals.at(a) < vals.at(b);
  879. });
  880. }
  881. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  882. { \
  883. const std::string skey(key); \
  884. const int kid = gguf_find_key(ctx, skey.c_str()); \
  885. if (kid >= 0) { \
  886. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  887. if (ktype != (type)) { \
  888. die_fmt("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype)); \
  889. } \
  890. (dst) = func(ctx, kid); \
  891. } else if (req) { \
  892. die_fmt("key not found in model: %s", skey.c_str()); \
  893. } \
  894. }
  895. bool are_same_layout(struct ggml_tensor * a, struct ggml_tensor * b) {
  896. GGML_ASSERT(a != NULL);
  897. GGML_ASSERT(b != NULL);
  898. GGML_ASSERT(a->type == b->type);
  899. GGML_ASSERT(ggml_are_same_shape(a, b));
  900. GGML_ASSERT(ggml_is_contiguous(a) && ggml_is_contiguous(b));
  901. return true;
  902. }
  903. void read_tensor_by_name(struct ggml_tensor * dst, struct ggml_context * ctx, const char * name) {
  904. if (dst == NULL) {
  905. return;
  906. }
  907. struct ggml_tensor * t = ggml_get_tensor(ctx, name);
  908. GGML_ASSERT(are_same_layout(dst, t));
  909. memcpy(dst->data, t->data, ggml_nbytes(t));
  910. if (strlen(ggml_get_name(dst)) == 0) {
  911. ggml_set_name(dst, name);
  912. }
  913. }
  914. void load_opt_context_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct ggml_opt_context * opt) {
  915. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  916. uint32_t file_version;
  917. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_FILE_VERSION);
  918. GGML_ASSERT(file_version == 0);
  919. GGUF_GET_KEY(fctx, opt->params.past, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT);
  920. GGUF_GET_KEY(fctx, opt->iter, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ITERATION_COUNT);
  921. GGUF_GET_KEY(fctx, opt->just_initialized, gguf_get_val_bool, GGUF_TYPE_BOOL, true, LLM_KV_OPTIMIZER_JUST_INITIALIZED);
  922. uint64_t nx;
  923. GGUF_GET_KEY(fctx, nx, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_OPTIMIZER_PARAMETER_COUNT);
  924. opt->nx = (size_t) nx;
  925. // don't call ggml_opt_init until optimizer type and optimizer specific parameters are know
  926. std::string opt_type;
  927. GGUF_GET_KEY(fctx, opt_type, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_OPTIMIZER_TYPE);
  928. if (opt_type == LLM_KV_OPTIMIZER_TYPE_ADAM) {
  929. opt->params.type = GGML_OPT_ADAM;
  930. GGUF_GET_KEY(fctx, opt->adam.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS);
  931. GGUF_GET_KEY(fctx, opt->adam.fx_prev, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS);
  932. GGUF_GET_KEY(fctx, opt->adam.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT);
  933. GGML_ASSERT(opt->ctx != NULL);
  934. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  935. read_tensor_by_name(opt->adam.m, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  936. read_tensor_by_name(opt->adam.v, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  937. read_tensor_by_name(opt->adam.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  938. } else if (opt_type == LLM_KV_OPTIMIZER_TYPE_LBFGS) {
  939. opt->params.type = GGML_OPT_LBFGS;
  940. GGUF_GET_KEY(fctx, opt->params.lbfgs.m, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT);
  941. GGUF_GET_KEY(fctx, opt->lbfgs.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS);
  942. GGUF_GET_KEY(fctx, opt->lbfgs.step, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP);
  943. GGUF_GET_KEY(fctx, opt->lbfgs.j, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J);
  944. GGUF_GET_KEY(fctx, opt->lbfgs.k, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K);
  945. GGUF_GET_KEY(fctx, opt->lbfgs.end, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END);
  946. GGUF_GET_KEY(fctx, opt->lbfgs.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT);
  947. GGML_ASSERT(opt->ctx != NULL);
  948. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  949. read_tensor_by_name(opt->lbfgs.x, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  950. read_tensor_by_name(opt->lbfgs.xp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  951. read_tensor_by_name(opt->lbfgs.g, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  952. read_tensor_by_name(opt->lbfgs.gp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  953. read_tensor_by_name(opt->lbfgs.d, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  954. read_tensor_by_name(opt->lbfgs.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  955. read_tensor_by_name(opt->lbfgs.lmal, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  956. read_tensor_by_name(opt->lbfgs.lmys, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  957. read_tensor_by_name(opt->lbfgs.lms, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  958. read_tensor_by_name(opt->lbfgs.lmy, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  959. } else {
  960. die("unknown optimizer type");
  961. }
  962. }
  963. void save_opt_context_gguf(struct gguf_context * fctx, struct ggml_opt_context * opt) {
  964. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_FILE_VERSION, 0);
  965. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT, opt->params.past);
  966. gguf_set_val_u64(fctx, LLM_KV_OPTIMIZER_PARAMETER_COUNT, (uint64_t) opt->nx);
  967. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ITERATION_COUNT, opt->iter);
  968. gguf_set_val_bool(fctx, LLM_KV_OPTIMIZER_JUST_INITIALIZED, opt->just_initialized);
  969. switch (opt->params.type) {
  970. case GGML_OPT_ADAM:
  971. {
  972. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_ADAM);
  973. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS, opt->adam.fx_best);
  974. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS, opt->adam.fx_prev);
  975. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT, opt->adam.n_no_improvement);
  976. ggml_set_name(opt->adam.m, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  977. ggml_set_name(opt->adam.v, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  978. if (opt->adam.pf) {
  979. ggml_set_name(opt->adam.pf, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  980. }
  981. gguf_add_tensor(fctx, opt->adam.m);
  982. gguf_add_tensor(fctx, opt->adam.v);
  983. if (opt->adam.pf) {
  984. gguf_add_tensor(fctx, opt->adam.pf);
  985. }
  986. } break;
  987. case GGML_OPT_LBFGS:
  988. {
  989. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_LBFGS);
  990. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT, opt->params.lbfgs.m);
  991. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS, opt->lbfgs.fx_best);
  992. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP, opt->lbfgs.step);
  993. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J, opt->lbfgs.j);
  994. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K, opt->lbfgs.k);
  995. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END, opt->lbfgs.end);
  996. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT, opt->lbfgs.n_no_improvement);
  997. ggml_set_name(opt->lbfgs.x, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  998. ggml_set_name(opt->lbfgs.xp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  999. ggml_set_name(opt->lbfgs.g, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  1000. ggml_set_name(opt->lbfgs.gp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  1001. ggml_set_name(opt->lbfgs.d, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  1002. if (opt->lbfgs.pf) {
  1003. ggml_set_name(opt->lbfgs.pf, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  1004. }
  1005. ggml_set_name(opt->lbfgs.lmal, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  1006. ggml_set_name(opt->lbfgs.lmys, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  1007. ggml_set_name(opt->lbfgs.lms, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  1008. ggml_set_name(opt->lbfgs.lmy, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  1009. gguf_add_tensor(fctx, opt->lbfgs.x);
  1010. gguf_add_tensor(fctx, opt->lbfgs.xp);
  1011. gguf_add_tensor(fctx, opt->lbfgs.g);
  1012. gguf_add_tensor(fctx, opt->lbfgs.gp);
  1013. gguf_add_tensor(fctx, opt->lbfgs.d);
  1014. if (opt->lbfgs.pf) {
  1015. gguf_add_tensor(fctx, opt->lbfgs.pf);
  1016. }
  1017. gguf_add_tensor(fctx, opt->lbfgs.lmal);
  1018. gguf_add_tensor(fctx, opt->lbfgs.lmys);
  1019. gguf_add_tensor(fctx, opt->lbfgs.lms);
  1020. gguf_add_tensor(fctx, opt->lbfgs.lmy);
  1021. } break;
  1022. }
  1023. }
  1024. void load_llama_model_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model) {
  1025. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  1026. std::string arch;
  1027. std::vector<char> keybuf;
  1028. keybuf.resize(512);
  1029. auto kv = [&arch, &keybuf](const char * key) -> const char * {
  1030. snprintf(keybuf.data(), keybuf.size(), key, arch.c_str());
  1031. return keybuf.data();
  1032. };
  1033. std::vector<char> tn_buf;
  1034. tn_buf.resize(GGML_MAX_NAME);
  1035. auto tn = [&tn_buf](const char * key) -> const char * {
  1036. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", key);
  1037. return tn_buf.data();
  1038. };
  1039. auto tni = [&tn_buf](const char * key, int bid) -> const char * {
  1040. snprintf(tn_buf.data(), tn_buf.size(), key, bid);
  1041. std::string s = tn_buf.data();
  1042. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", s.c_str());
  1043. return tn_buf.data();
  1044. };
  1045. GGUF_GET_KEY(fctx, arch, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_GENERAL_ARCHITECTURE);
  1046. GGML_ASSERT(arch == "llama");
  1047. uint32_t ftype_u;
  1048. GGUF_GET_KEY(fctx, ftype_u, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_GENERAL_FILE_TYPE);
  1049. GGML_ASSERT((enum llama_ftype) ftype_u == LLAMA_FTYPE_ALL_F32);
  1050. // n_ctx was not saved in earlier checkpoint file versions, so we make it optional here
  1051. GGUF_GET_KEY(fctx, model->hparams.n_ctx, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_CONTEXT_LENGTH));
  1052. GGUF_GET_KEY(fctx, model->hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1053. GGUF_GET_KEY(fctx, model->hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1054. GGUF_GET_KEY(fctx, model->hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1055. GGUF_GET_KEY(fctx, model->hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1056. model->hparams.n_rot = model->hparams.n_embd / model->hparams.n_head;
  1057. GGUF_GET_KEY(fctx, model->hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1058. float rope_freq_scale = 1.0f;
  1059. 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));
  1060. GGUF_GET_KEY(fctx, model->hparams.rope_freq_base, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1061. GGUF_GET_KEY(fctx, rope_freq_scale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1062. if (rope_freq_scale != 1.0f) {
  1063. model->hparams.rope_freq_scale = 1.0f / rope_freq_scale;
  1064. }
  1065. init_model(model);
  1066. read_tensor_by_name(model->tok_embeddings, f_ggml_ctx, tn(LLM_TENSOR_TOKEN_EMBD));
  1067. read_tensor_by_name(model->norm, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT_NORM));
  1068. read_tensor_by_name(model->output, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT));
  1069. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  1070. auto & layer = model->layers[i];
  1071. read_tensor_by_name(layer.attention_norm, f_ggml_ctx, tni(LLM_TENSOR_ATTN_NORM, i));
  1072. read_tensor_by_name(layer.wq, f_ggml_ctx, tni(LLM_TENSOR_ATTN_Q, i));
  1073. read_tensor_by_name(layer.wk, f_ggml_ctx, tni(LLM_TENSOR_ATTN_K, i));
  1074. read_tensor_by_name(layer.wv, f_ggml_ctx, tni(LLM_TENSOR_ATTN_V, i));
  1075. read_tensor_by_name(layer.wo, f_ggml_ctx, tni(LLM_TENSOR_ATTN_OUT, i));
  1076. read_tensor_by_name(layer.ffn_norm, f_ggml_ctx, tni(LLM_TENSOR_FFN_NORM, i));
  1077. read_tensor_by_name(layer.w1, f_ggml_ctx, tni(LLM_TENSOR_FFN_GATE, i));
  1078. read_tensor_by_name(layer.w2, f_ggml_ctx, tni(LLM_TENSOR_FFN_DOWN, i));
  1079. read_tensor_by_name(layer.w3, f_ggml_ctx, tni(LLM_TENSOR_FFN_UP, i));
  1080. }
  1081. }
  1082. void save_llama_model_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model) {
  1083. const char * arch = "llama";
  1084. enum llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1085. std::vector<char> keybuf;
  1086. keybuf.resize(512);
  1087. auto kv = [arch, &keybuf](const char * key) -> const char * {
  1088. snprintf(keybuf.data(), keybuf.size(), key, arch);
  1089. return keybuf.data();
  1090. };
  1091. // set arch
  1092. gguf_set_val_str(fctx, LLM_KV_GENERAL_ARCHITECTURE, arch);
  1093. gguf_set_val_u32(fctx, LLM_KV_GENERAL_FILE_TYPE, ftype);
  1094. // set hparams
  1095. gguf_set_val_u32(fctx, kv(LLM_KV_CONTEXT_LENGTH), model->hparams.n_ctx );
  1096. gguf_set_val_u32(fctx, kv(LLM_KV_EMBEDDING_LENGTH), model->hparams.n_embd );
  1097. gguf_set_val_u32(fctx, kv(LLM_KV_FEED_FORWARD_LENGTH), model->hparams.n_ff );
  1098. gguf_set_val_u32(fctx, kv(LLM_KV_ATTENTION_HEAD_COUNT), model->hparams.n_head );
  1099. gguf_set_val_u32(fctx, kv(LLM_KV_BLOCK_COUNT), model->hparams.n_layer );
  1100. gguf_set_val_u32(fctx, kv(LLM_KV_ROPE_DIMENSION_COUNT), model->hparams.n_rot );
  1101. gguf_set_val_f32(fctx, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS), model->hparams.f_norm_rms_eps );
  1102. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_FREQ_BASE), model->hparams.rope_freq_base ); // TODO load in llama.cpp
  1103. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_SCALE_LINEAR), 1.0f / model->hparams.rope_freq_scale );
  1104. // set vocab by copying from vocab_model gguf file
  1105. {
  1106. struct gguf_init_params params = {
  1107. /*.no_alloc = */ false,
  1108. /*.ctx = */ NULL,
  1109. };
  1110. struct gguf_context * vctx = gguf_init_from_file(fn_vocab_model, params);
  1111. const int token_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_LIST));
  1112. if (token_idx == -1) {
  1113. die("cannot find tokenizer vocab in model file");
  1114. }
  1115. const uint32_t n_vocab = gguf_get_arr_n(vctx, token_idx);
  1116. const int score_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_SCORES));
  1117. if (score_idx == -1) {
  1118. die("cannot find tokenizer scores in model file");
  1119. }
  1120. const float * scores = (const float * ) gguf_get_arr_data(vctx, score_idx);
  1121. const int toktype_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE));
  1122. if (toktype_idx == -1) {
  1123. die("cannot find token type list in GGUF file");
  1124. }
  1125. const int * toktypes = (const int * ) gguf_get_arr_data(vctx, toktype_idx);
  1126. std::string tokenizer_name;
  1127. GGUF_GET_KEY(vctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1128. gguf_set_val_str(fctx, kv(LLM_KV_TOKENIZER_MODEL), tokenizer_name.c_str());
  1129. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_SCORES), GGUF_TYPE_FLOAT32, scores, n_vocab);
  1130. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE), GGUF_TYPE_INT32, toktypes, n_vocab);
  1131. int32_t special_bos_id = 1;
  1132. int32_t special_eos_id = 2;
  1133. int32_t special_unk_id = 0;
  1134. int32_t special_sep_id = -1;
  1135. int32_t special_pad_id = -1;
  1136. if (tokenizer_name == "llama") {
  1137. // default special tokens
  1138. special_bos_id = 1;
  1139. special_eos_id = 2;
  1140. special_unk_id = 0;
  1141. special_sep_id = -1;
  1142. special_pad_id = -1;
  1143. } else if (tokenizer_name == "gpt2") {
  1144. // read and copy bpe merges
  1145. const int merges_keyidx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_MERGES));
  1146. if (merges_keyidx == -1) {
  1147. die("cannot find tokenizer merges in model file");
  1148. }
  1149. const int n_merges = gguf_get_arr_n(vctx, merges_keyidx);
  1150. std::vector<const char*> merges;
  1151. merges.resize(n_merges);
  1152. for (int i = 0; i < n_merges; i++) {
  1153. merges[i] = gguf_get_arr_str(vctx, merges_keyidx, i);
  1154. }
  1155. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_MERGES), merges.data(), n_merges);
  1156. // default special tokens
  1157. special_bos_id = 11;
  1158. special_eos_id = 11;
  1159. special_unk_id = -1;
  1160. special_sep_id = -1;
  1161. special_pad_id = -1;
  1162. } else {
  1163. fprintf(stderr, "%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1164. fprintf(stderr, "%s: using default tokenizer: 'llama'", __func__);
  1165. }
  1166. std::vector<const char*> tokens;
  1167. tokens.resize(n_vocab);
  1168. for (uint32_t i = 0; i < n_vocab; i++) {
  1169. tokens[i] = gguf_get_arr_str(vctx, token_idx, i);
  1170. }
  1171. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_LIST), tokens.data(), n_vocab);
  1172. GGUF_GET_KEY(vctx, special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1173. GGUF_GET_KEY(vctx, special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1174. GGUF_GET_KEY(vctx, special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1175. GGUF_GET_KEY(vctx, special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1176. GGUF_GET_KEY(vctx, special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1177. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_BOS_ID), special_bos_id);
  1178. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_EOS_ID), special_eos_id);
  1179. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_UNK_ID), special_unk_id);
  1180. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_SEP_ID), special_sep_id);
  1181. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_PAD_ID), special_pad_id);
  1182. gguf_free(vctx);
  1183. }
  1184. // add tensors
  1185. gguf_add_tensor(fctx, model->tok_embeddings);
  1186. gguf_add_tensor(fctx, model->norm);
  1187. gguf_add_tensor(fctx, model->output);
  1188. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  1189. auto & layer = model->layers[i];
  1190. gguf_add_tensor(fctx, layer.attention_norm);
  1191. gguf_add_tensor(fctx, layer.wq);
  1192. gguf_add_tensor(fctx, layer.wk);
  1193. gguf_add_tensor(fctx, layer.wv);
  1194. gguf_add_tensor(fctx, layer.wo);
  1195. gguf_add_tensor(fctx, layer.ffn_norm);
  1196. gguf_add_tensor(fctx, layer.w1);
  1197. gguf_add_tensor(fctx, layer.w2);
  1198. gguf_add_tensor(fctx, layer.w3);
  1199. }
  1200. }
  1201. void save_llama_model_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model) {
  1202. struct gguf_context * fctx = gguf_init_empty();
  1203. save_llama_model_gguf(fctx, fn_vocab_model, model);
  1204. // write file
  1205. const bool only_meta = false;
  1206. gguf_write_to_file(fctx, filename, only_meta);
  1207. gguf_free(fctx);
  1208. }
  1209. void load_checkpoint_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1210. load_llama_model_gguf(fctx, f_ggml_ctx, model);
  1211. uint32_t file_version;
  1212. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_FILE_VERSION);
  1213. GGML_ASSERT(file_version == 0);
  1214. GGUF_GET_KEY(fctx, model->train_its, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_ITERATION_COUNT);
  1215. GGUF_GET_KEY(fctx, model->train_samples, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_SAMPLE_COUNT);
  1216. GGUF_GET_KEY(fctx, model->train_tokens, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_TOKEN_COUNT);
  1217. load_opt_context_gguf(fctx, f_ggml_ctx, opt);
  1218. }
  1219. void save_checkpoint_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1220. save_llama_model_gguf(fctx, fn_vocab_model, model);
  1221. gguf_set_val_u32(fctx, LLM_KV_TRAINING_FILE_VERSION, 0);
  1222. gguf_set_val_u32(fctx, LLM_KV_TRAINING_ITERATION_COUNT, model->train_its);
  1223. gguf_set_val_u32(fctx, LLM_KV_TRAINING_SAMPLE_COUNT, model->train_samples);
  1224. gguf_set_val_u32(fctx, LLM_KV_TRAINING_TOKEN_COUNT, model->train_tokens);
  1225. save_opt_context_gguf(fctx, opt);
  1226. }
  1227. bool load_checkpoint_file(const char * filename, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1228. struct ggml_context * f_ggml_ctx;
  1229. struct gguf_init_params params;
  1230. params.no_alloc = false;
  1231. params.ctx = &f_ggml_ctx;
  1232. struct gguf_context * fctx = gguf_init_from_file(filename, params);
  1233. if (fctx == NULL) {
  1234. return false;
  1235. }
  1236. load_checkpoint_gguf(fctx, f_ggml_ctx, model, opt);
  1237. return true;
  1238. }
  1239. void save_checkpoint_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model, struct ggml_opt_context * opt) {
  1240. struct gguf_context * fctx = gguf_init_empty();
  1241. save_checkpoint_gguf(fctx, fn_vocab_model, model, opt);
  1242. // write file
  1243. const bool only_meta = false;
  1244. gguf_write_to_file(fctx, filename, only_meta);
  1245. gguf_free(fctx);
  1246. }
  1247. float cosine_decay(const int decay_steps, const float minimum, int step) {
  1248. if (step > decay_steps) {
  1249. step = decay_steps;
  1250. }
  1251. const float cosine_decay = 0.50f*(1.0f + cosf(3.14159265359f*step/decay_steps));
  1252. const float decay = (1 - minimum)*cosine_decay + minimum;
  1253. return decay;
  1254. }
  1255. float cosine_decay_restart(int decay_steps, const float minimum, int step, float restart_step_mult, bool enable_restart) {
  1256. if (enable_restart) {
  1257. while (step > decay_steps) {
  1258. step -= decay_steps;
  1259. decay_steps = (int) restart_step_mult * decay_steps;
  1260. }
  1261. }
  1262. return cosine_decay(decay_steps, minimum, step);
  1263. }
  1264. struct train_params {
  1265. const char * fn_vocab_model;
  1266. const char * fn_train_data;
  1267. const char * fn_checkpoint_in;
  1268. const char * fn_checkpoint_out;
  1269. const char * fn_model_out;
  1270. uint32_t seed;
  1271. int n_ctx;
  1272. int n_embd;
  1273. int n_head;
  1274. int n_layer;
  1275. int n_ff;
  1276. int n_threads;
  1277. int n_batch;
  1278. int n_examples;
  1279. float f_norm_rms_eps;
  1280. float rope_freq_base;
  1281. float rope_freq_scale;
  1282. int print_info_interval;
  1283. bool samples_start_after_nl;
  1284. bool use_adam;
  1285. bool use_flash;
  1286. bool use_checkpointing;
  1287. bool use_alloc;
  1288. // only adam
  1289. int warmup;
  1290. int cos_decay_steps;
  1291. float cos_decay_restart;
  1292. float cos_decay_min;
  1293. bool enable_restart;
  1294. int opt_past;
  1295. float opt_delta;
  1296. int opt_max_no_improvement;
  1297. int lbfgs_n_iter;
  1298. int adam_n_iter;
  1299. float adam_alpha;
  1300. float adam_min_alpha;
  1301. float adam_decay;
  1302. int adam_decay_min_ndim;
  1303. float adam_beta1;
  1304. float adam_beta2;
  1305. float adam_gclip;
  1306. float adam_eps_f;
  1307. int mem_model_gb;
  1308. int mem_compute_gb;
  1309. int mem_compute0_gb;
  1310. };
  1311. struct train_params get_default_train_params() {
  1312. struct train_params params;
  1313. params.fn_vocab_model = "ggml-vic7b-uncensored-q4_0.bin";
  1314. params.fn_train_data = "shakespeare.txt";
  1315. params.fn_checkpoint_in = "checkpoint.bin";
  1316. params.fn_checkpoint_out = "checkpoint.bin";
  1317. params.fn_model_out = "ggml-checkpoint-f32.bin";
  1318. params.seed = -1;
  1319. params.n_ctx = 128;
  1320. params.n_embd = 256;
  1321. params.n_head = 8;
  1322. params.n_layer = 16;
  1323. params.n_ff = 768;
  1324. params.n_threads = 6;
  1325. params.n_batch = 8;
  1326. params.n_examples = 1;
  1327. params.f_norm_rms_eps = 1e-5;
  1328. params.rope_freq_base = 10000.0f;
  1329. params.rope_freq_scale = 1.0f;
  1330. params.print_info_interval = 1;
  1331. params.samples_start_after_nl = false;
  1332. params.use_adam = true;
  1333. params.use_flash = true;
  1334. params.use_checkpointing = true;
  1335. params.use_alloc = true;
  1336. params.opt_past = 0;
  1337. params.opt_delta = 1e-5f;
  1338. params.opt_max_no_improvement = 0;
  1339. // only adam
  1340. params.warmup = 100;
  1341. params.cos_decay_steps = 1000;
  1342. params.cos_decay_restart = 1.1f;
  1343. params.cos_decay_min = 0.1f;
  1344. params.enable_restart = false;
  1345. params.lbfgs_n_iter = 256;
  1346. params.adam_n_iter = 256;
  1347. params.adam_alpha = 1e-3f;
  1348. params.adam_min_alpha = 0;
  1349. params.adam_decay = 1e-1f;
  1350. params.adam_decay_min_ndim = 2;
  1351. params.adam_beta1 = 0.9f;
  1352. params.adam_beta2 = 0.999f;
  1353. params.adam_gclip = 1.0f;
  1354. params.adam_eps_f = 0.0f;
  1355. params.mem_model_gb = 2;
  1356. params.mem_compute_gb = 24;
  1357. params.mem_compute0_gb = 8;
  1358. return params;
  1359. }
  1360. void train_print_usage(int /*argc*/, char ** argv, const struct train_params * params) {
  1361. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  1362. fprintf(stderr, "\n");
  1363. fprintf(stderr, "options:\n");
  1364. fprintf(stderr, " -h, --help show this help message and exit\n");
  1365. fprintf(stderr, " --vocab-model FNAME model path from which to load vocab (default '%s')\n", params->fn_vocab_model);
  1366. fprintf(stderr, " --train-data FNAME path from which to load training data (default '%s')\n", params->fn_train_data);
  1367. fprintf(stderr, " --checkpoint-in FNAME path from which to load training checkpoint (default '%s')\n", params->fn_checkpoint_in);
  1368. fprintf(stderr, " --checkpoint-out FNAME path to save training checkpoint (default '%s')\n", params->fn_checkpoint_out);
  1369. fprintf(stderr, " --model-out FNAME path to save ggml model (default '%s')\n", params->fn_model_out);
  1370. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for -1)\n");
  1371. fprintf(stderr, " -c N, --ctx N Context size used during training (default %d)\n", params->n_ctx);
  1372. fprintf(stderr, " --embd N Embedding size used for new models (default %d)\n", params->n_embd);
  1373. fprintf(stderr, " --ff N Feedforward size used for new models. (default %d)\n", params->n_ff);
  1374. fprintf(stderr, " --head N Number of heads for new models (default %d)\n", params->n_head);
  1375. fprintf(stderr, " --layer N Number of layers for new models (default %d)\n", params->n_layer);
  1376. fprintf(stderr, " --norm-rms-eps F RMS-Norm epsilon value (default %f)\n", params->f_norm_rms_eps);
  1377. fprintf(stderr, " --rope-freq-base F Frequency base for ROPE (default %f)\n", params->rope_freq_base);
  1378. fprintf(stderr, " --rope-freq-scale F Frequency scale for ROPE (default %f)\n", params->rope_freq_scale);
  1379. fprintf(stderr, " -t N, --threads N Number of threads (default %d)\n", params->n_threads);
  1380. fprintf(stderr, " -b N, --batch N Parallel batch size (default %d)\n", params->n_batch);
  1381. fprintf(stderr, " -n N, --examples N Number of examples to train (default %d)\n", params->n_examples);
  1382. fprintf(stderr, " --print-info-interval N Print infos during training each N examples (default %d)\n", params->print_info_interval);
  1383. fprintf(stderr, " --samples-after-nl Training samples start after newlines. (default %s)\n", params->samples_start_after_nl ? "on" : "off");
  1384. fprintf(stderr, " --use-lbfgs Use LBFGS optimizer instead of default Adam\n");
  1385. fprintf(stderr, " --use-adam Use Adam optimizer (default)\n");
  1386. fprintf(stderr, " --no-flash Don't use flash attention \n");
  1387. fprintf(stderr, " --use-flash Use flash attention (default)\n");
  1388. fprintf(stderr, " --no-checkpointing Don't use gradient checkpointing\n");
  1389. fprintf(stderr, " --use-checkpointing Use gradient checkpointing (default)\n");
  1390. fprintf(stderr, " --no-alloc Don't use allocator\n");
  1391. fprintf(stderr, " --use-alloc Use allocator (default)\n");
  1392. fprintf(stderr, " --warmup N Only for Adam optimizer. Number of warmup steps (default %d)\n", params->warmup);
  1393. fprintf(stderr, " --cos-decay-steps N Only for Adam optimizer. Number of cosine decay steps (default %d)\n", params->cos_decay_steps);
  1394. fprintf(stderr, " --cos-decay-restart N Only for Adam optimizer. Increase of cosine decay steps after restart (default %f)\n", params->cos_decay_restart);
  1395. fprintf(stderr, " --cos-decay-min N Only for Adam optimizer. Cosine decay minimum (default %f)\n", params->cos_decay_min);
  1396. fprintf(stderr, " --enable-restart N Only for Adam optimizer. Enable restarts of cos-decay %s\n", params->enable_restart ? "(default)" : "");
  1397. fprintf(stderr, " --disable-restart N Only for Adam optimizer. Disable restarts of cos-decay %s\n", !params->enable_restart ? "(default)" : "");
  1398. fprintf(stderr, " --opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero. (default %d)\n", params->opt_past);
  1399. fprintf(stderr, " --opt-delta N Maximum delta for delta convergence test. Disabled when <= zero. (default %f)\n", params->opt_delta);
  1400. 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);
  1401. fprintf(stderr, " --adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero. (default %f)\n", params->adam_eps_f);
  1402. fprintf(stderr, " --adam-iter N Maximum number of Adam optimization iterations for each batch (default %d)\n", params->adam_n_iter);
  1403. fprintf(stderr, " --adam-alpha N Adam learning rate alpha (default %f)\n", params->adam_alpha);
  1404. fprintf(stderr, " --adam-min-alpha N Adam minimum learning rate alpha - including warmup phase (default %f)\n", params->adam_min_alpha);
  1405. fprintf(stderr, " --adam-decay N AdamW weight decay. Values greater zero enable AdamW instead of regular Adam. (default %f)\n", params->adam_decay);
  1406. 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);
  1407. 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);
  1408. 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);
  1409. fprintf(stderr, " --adam-gclip N AdamW gradient clipping. Disabled when zero. (default %f)\n", params->adam_gclip);
  1410. fprintf(stderr, " --lbfgs-iter N Maximum number of LBFGS optimization iterations for each batch (default %d)\n", params->lbfgs_n_iter);
  1411. fprintf(stderr, " --mem-model N Memory to allocate for model and cache in gigabytes. (default %d)\n", params->mem_model_gb);
  1412. fprintf(stderr, " --mem-compute N Memory to allocate for compute in gigabytes. (default %d)\n", params->mem_compute_gb);
  1413. fprintf(stderr, " --mem-compute0 N Memory to allocate for automatic memory allocator in gigabytes. (default %d)\n", params->mem_compute0_gb);
  1414. fprintf(stderr, "\n");
  1415. }
  1416. bool train_params_parse(int argc, char ** argv, struct train_params * params) {
  1417. bool invalid_param = false;
  1418. std::string arg;
  1419. struct train_params default_params = get_default_train_params();
  1420. const std::string arg_prefix = "--";
  1421. for (int i = 1; i < argc; i++) {
  1422. arg = argv[i];
  1423. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  1424. std::replace(arg.begin(), arg.end(), '_', '-');
  1425. }
  1426. if (arg == "--vocab-model") {
  1427. if (++i >= argc) {
  1428. invalid_param = true;
  1429. break;
  1430. }
  1431. params->fn_vocab_model = argv[i];
  1432. } else if (arg == "--train-data") {
  1433. if (++i >= argc) {
  1434. invalid_param = true;
  1435. break;
  1436. }
  1437. params->fn_train_data = argv[i];
  1438. } else if (arg == "--checkpoint-in") {
  1439. if (++i >= argc) {
  1440. invalid_param = true;
  1441. break;
  1442. }
  1443. params->fn_checkpoint_in = argv[i];
  1444. } else if (arg == "--checkpoint-out") {
  1445. if (++i >= argc) {
  1446. invalid_param = true;
  1447. break;
  1448. }
  1449. params->fn_checkpoint_out = argv[i];
  1450. } else if (arg == "--model-out") {
  1451. if (++i >= argc) {
  1452. invalid_param = true;
  1453. break;
  1454. }
  1455. params->fn_model_out = argv[i];
  1456. } else if (arg == "-s" || arg == "--seed") {
  1457. if (++i >= argc) {
  1458. invalid_param = true;
  1459. break;
  1460. }
  1461. params->seed = std::stoi(argv[i]);
  1462. } else if (arg == "-c" || arg == "--ctx") {
  1463. if (++i >= argc) {
  1464. invalid_param = true;
  1465. break;
  1466. }
  1467. params->n_ctx = std::stoi(argv[i]);
  1468. } else if (arg == "--embd") {
  1469. if (++i >= argc) {
  1470. invalid_param = true;
  1471. break;
  1472. }
  1473. params->n_embd = std::stoi(argv[i]);
  1474. } else if (arg == "--ff") {
  1475. if (++i >= argc) {
  1476. invalid_param = true;
  1477. break;
  1478. }
  1479. params->n_ff = std::stoi(argv[i]);
  1480. } else if (arg == "--head") {
  1481. if (++i >= argc) {
  1482. invalid_param = true;
  1483. break;
  1484. }
  1485. params->n_head = std::stoi(argv[i]);
  1486. } else if (arg == "--layer") {
  1487. if (++i >= argc) {
  1488. invalid_param = true;
  1489. break;
  1490. }
  1491. params->n_layer = std::stoi(argv[i]);
  1492. } else if (arg == "--norm-rms-eps") {
  1493. if (++i >= argc) {
  1494. invalid_param = true;
  1495. break;
  1496. }
  1497. params->f_norm_rms_eps = std::stof(argv[i]);
  1498. } else if (arg == "--rope-freq-base") {
  1499. if (++i >= argc) {
  1500. invalid_param = true;
  1501. break;
  1502. }
  1503. params->rope_freq_base = std::stof(argv[i]);
  1504. } else if (arg == "--rope-freq-scale") {
  1505. if (++i >= argc) {
  1506. invalid_param = true;
  1507. break;
  1508. }
  1509. params->rope_freq_scale = std::stof(argv[i]);
  1510. } else if (arg == "-t" || arg == "--threads") {
  1511. if (++i >= argc) {
  1512. invalid_param = true;
  1513. break;
  1514. }
  1515. params->n_threads = std::stoi(argv[i]);
  1516. } else if (arg == "-b" || arg == "--batch") {
  1517. if (++i >= argc) {
  1518. invalid_param = true;
  1519. break;
  1520. }
  1521. params->n_batch = std::stoi(argv[i]);
  1522. } else if (arg == "-n" || arg == "--examples") {
  1523. if (++i >= argc) {
  1524. invalid_param = true;
  1525. break;
  1526. }
  1527. params->n_examples = std::stoi(argv[i]);
  1528. } else if (arg == "--print-info-interval") {
  1529. if (++i >= argc) {
  1530. invalid_param = true;
  1531. break;
  1532. }
  1533. params->print_info_interval = std::stoi(argv[i]);
  1534. } else if (arg == "--samples-after-nl") {
  1535. params->samples_start_after_nl = true;
  1536. } else if (arg == "--use-lbfgs") {
  1537. params->use_adam = false;
  1538. } else if (arg == "--use-adam") {
  1539. params->use_adam = true;
  1540. } else if (arg == "--no-flash") {
  1541. params->use_flash = false;
  1542. } else if (arg == "--use-flash") {
  1543. params->use_flash = true;
  1544. } else if (arg == "--no-checkpointing") {
  1545. params->use_checkpointing = false;
  1546. } else if (arg == "--use-checkpointing") {
  1547. params->use_checkpointing = true;
  1548. } else if (arg == "--no-alloc") {
  1549. params->use_alloc = false;
  1550. } else if (arg == "--use-alloc") {
  1551. params->use_alloc = true;
  1552. } else if (arg == "--warmup") {
  1553. if (++i >= argc) {
  1554. invalid_param = true;
  1555. break;
  1556. }
  1557. params->warmup = std::stoi(argv[i]);
  1558. } else if (arg == "--cos-decay-steps") {
  1559. if (++i >= argc) {
  1560. invalid_param = true;
  1561. break;
  1562. }
  1563. params->cos_decay_steps = std::stof(argv[i]);
  1564. } else if (arg == "--cos-decay-restart") {
  1565. if (++i >= argc) {
  1566. invalid_param = true;
  1567. break;
  1568. }
  1569. params->cos_decay_restart = std::stof(argv[i]);
  1570. } else if (arg == "--cos-decay-min") {
  1571. if (++i >= argc) {
  1572. invalid_param = true;
  1573. break;
  1574. }
  1575. params->cos_decay_min = std::stof(argv[i]);
  1576. } else if (arg == "--enable-restart") {
  1577. params->enable_restart = true;
  1578. } else if (arg == "--disable-restart") {
  1579. params->enable_restart = false;
  1580. } else if (arg == "--opt-past") {
  1581. if (++i >= argc) {
  1582. invalid_param = true;
  1583. break;
  1584. }
  1585. params->opt_past = std::stoi(argv[i]);
  1586. } else if (arg == "--opt-delta") {
  1587. if (++i >= argc) {
  1588. invalid_param = true;
  1589. break;
  1590. }
  1591. params->opt_delta = std::stof(argv[i]);
  1592. } else if (arg == "--opt-max-no-improvement") {
  1593. if (++i >= argc) {
  1594. invalid_param = true;
  1595. break;
  1596. }
  1597. params->opt_max_no_improvement = std::stoi(argv[i]);
  1598. } else if (arg == "--adam-epsf") {
  1599. if (++i >= argc) {
  1600. invalid_param = true;
  1601. break;
  1602. }
  1603. params->adam_eps_f = std::stof(argv[i]);
  1604. } else if (arg == "--adam-iter") {
  1605. if (++i >= argc) {
  1606. invalid_param = true;
  1607. break;
  1608. }
  1609. params->adam_n_iter = std::stoi(argv[i]);
  1610. } else if (arg == "--adam-alpha") {
  1611. if (++i >= argc) {
  1612. invalid_param = true;
  1613. break;
  1614. }
  1615. params->adam_alpha = std::stof(argv[i]);
  1616. } else if (arg == "--adam-min-alpha") {
  1617. if (++i >= argc) {
  1618. invalid_param = true;
  1619. break;
  1620. }
  1621. params->adam_min_alpha = std::stof(argv[i]);
  1622. } else if (arg == "--adam-decay") {
  1623. if (++i >= argc) {
  1624. invalid_param = true;
  1625. break;
  1626. }
  1627. params->adam_decay = std::stof(argv[i]);
  1628. } else if (arg == "--adam-decay-min-ndim") {
  1629. if (++i >= argc) {
  1630. invalid_param = true;
  1631. break;
  1632. }
  1633. params->adam_decay_min_ndim = std::stoi(argv[i]);
  1634. } else if (arg == "--adam-beta1") {
  1635. if (++i >= argc) {
  1636. invalid_param = true;
  1637. break;
  1638. }
  1639. params->adam_beta1 = std::stof(argv[i]);
  1640. } else if (arg == "--adam-beta2") {
  1641. if (++i >= argc) {
  1642. invalid_param = true;
  1643. break;
  1644. }
  1645. params->adam_beta2 = std::stof(argv[i]);
  1646. } else if (arg == "--adam-gclip") {
  1647. if (++i >= argc) {
  1648. invalid_param = true;
  1649. break;
  1650. }
  1651. params->adam_gclip = std::stof(argv[i]);
  1652. } else if (arg == "--lbfgs-iter") {
  1653. if (++i >= argc) {
  1654. invalid_param = true;
  1655. break;
  1656. }
  1657. params->lbfgs_n_iter = std::stoi(argv[i]);
  1658. } else if (arg == "--mem-model") {
  1659. if (++i >= argc) {
  1660. invalid_param = true;
  1661. break;
  1662. }
  1663. params->mem_model_gb = std::stoi(argv[i]);
  1664. } else if (arg == "--mem-compute") {
  1665. if (++i >= argc) {
  1666. invalid_param = true;
  1667. break;
  1668. }
  1669. params->mem_compute_gb = std::stoi(argv[i]);
  1670. } else if (arg == "--mem-compute0") {
  1671. if (++i >= argc) {
  1672. invalid_param = true;
  1673. break;
  1674. }
  1675. params->mem_compute0_gb = std::stoi(argv[i]);
  1676. } else if (arg == "-h" || arg == "--help") {
  1677. train_print_usage(argc, argv, &default_params);
  1678. exit(0);
  1679. } else {
  1680. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  1681. train_print_usage(argc, argv, &default_params);
  1682. exit(1);
  1683. }
  1684. }
  1685. if (invalid_param) {
  1686. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  1687. train_print_usage(argc, argv, &default_params);
  1688. exit(1);
  1689. }
  1690. return true;
  1691. }
  1692. struct opt_callback_data {
  1693. struct train_params * params;
  1694. struct ggml_opt_context * opt;
  1695. struct llama_context * lctx;
  1696. llama_token * tokens_data;
  1697. size_t tokens_size;
  1698. int * samples_data;
  1699. size_t samples_size;
  1700. int shuffle_countdown;
  1701. struct ggml_tensor * tokens_input;
  1702. struct ggml_tensor * target_logits;
  1703. struct ggml_tensor * target_probs;
  1704. };
  1705. void opt_callback(void * vdata, float * sched) {
  1706. struct opt_callback_data * data = (struct opt_callback_data *) vdata;
  1707. struct train_params * params = data->params;
  1708. struct ggml_opt_context * opt = data->opt;
  1709. int n_batch = params->n_batch;
  1710. *sched = (opt->iter < params->warmup)
  1711. ? (float) opt->iter / (float) params->warmup
  1712. : cosine_decay_restart(
  1713. params->cos_decay_steps,
  1714. params->cos_decay_min,
  1715. opt->iter - params->warmup,
  1716. params->cos_decay_restart,
  1717. params->enable_restart);
  1718. float min_sched = params->adam_min_alpha / params->adam_alpha;
  1719. *sched = min_sched + *sched * (1.0f - min_sched);
  1720. int impr_plot = std::isnan(opt->loss_after) ? 0 : -std::lround(1 + (opt->loss_before - opt->loss_after) * 10.0f);
  1721. 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);
  1722. if (data->shuffle_countdown < n_batch) {
  1723. printf("%s: reshuffle samples\n", __func__);
  1724. shuffle_ints(data->samples_data, data->samples_data + data->samples_size);
  1725. for (int i = 0; i < (int) data->samples_size; ++i) {
  1726. GGML_ASSERT(data->samples_data[i]+params->n_ctx-1 < (int) data->tokens_size);
  1727. }
  1728. data->shuffle_countdown = data->samples_size;
  1729. }
  1730. get_example_targets_batch(
  1731. data->lctx,
  1732. data->samples_data,
  1733. data->samples_size,
  1734. data->tokens_data,
  1735. data->tokens_size,
  1736. opt->iter,
  1737. data->tokens_input,
  1738. data->target_logits,
  1739. data->target_probs);
  1740. data->shuffle_countdown -= n_batch;
  1741. }
  1742. int main(int argc, char ** argv) {
  1743. struct train_params params = get_default_train_params();
  1744. if (!train_params_parse(argc, argv, &params)) {
  1745. return 1;
  1746. }
  1747. if (params.seed == LLAMA_DEFAULT_SEED) {
  1748. params.seed = time(NULL);
  1749. }
  1750. printf("%s: seed: %u\n", __func__, params.seed);
  1751. srand(params.seed);
  1752. struct llama_context_params llama_params = llama_context_default_params();
  1753. llama_params.vocab_only = true;
  1754. struct llama_model * lmodel = llama_load_model_from_file(params.fn_vocab_model, llama_params);
  1755. struct llama_context * lctx = llama_new_context_with_model(lmodel, llama_params);
  1756. printf("%s: tokenize training data\n", __func__);
  1757. std::vector<llama_token> train_tokens;
  1758. if (tokenize_file(lctx, params.fn_train_data, train_tokens) < 0) {
  1759. fprintf(stderr, "%s: failed to tokenize file '%s'\n", __func__, params.fn_train_data);
  1760. }
  1761. printf("%s: number of training tokens: %d\n", __func__, (int) train_tokens.size());
  1762. struct my_llama_model model;
  1763. model.hparams.n_vocab = llama_n_vocab(lctx);
  1764. model.hparams.n_ctx = params.n_ctx;
  1765. model.hparams.n_embd = params.n_embd;
  1766. model.hparams.n_head = params.n_head;
  1767. model.hparams.n_layer = params.n_layer;
  1768. model.hparams.n_ff = params.n_ff;
  1769. // llama.cpp requires n_rot to be exactly n_embd / n_head
  1770. model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  1771. model.hparams.f_norm_rms_eps = params.f_norm_rms_eps;
  1772. model.hparams.rope_freq_base = params.rope_freq_base;
  1773. model.hparams.rope_freq_scale = params.rope_freq_scale;
  1774. print_params(&model.hparams);
  1775. std::vector<size_t> token_noccurs;
  1776. std::vector<bool> token_notavail;
  1777. token_noccurs.resize(model.hparams.n_vocab, 0);
  1778. token_notavail.resize(model.hparams.n_vocab, true);
  1779. for (int i = 0; i < (int) train_tokens.size(); ++i) {
  1780. ++token_noccurs[train_tokens[i]];
  1781. token_notavail[train_tokens[i]] = false;
  1782. }
  1783. std::vector<float> token_freq;
  1784. token_freq.resize(model.hparams.n_vocab, 0);
  1785. int n_unique_tokens = 0;
  1786. for (int i = 0; i < (int) token_noccurs.size(); ++i) {
  1787. token_freq[i] = (float) token_noccurs[i] / (float) train_tokens.size();
  1788. n_unique_tokens += (token_noccurs[i] > 0) ? 1 : 0;
  1789. }
  1790. printf("%s: number of unique tokens: %d\n", __func__, n_unique_tokens);
  1791. struct ggml_init_params lcparams;
  1792. lcparams.mem_size = 1024ll*1024ll*1024ll*((size_t) params.mem_model_gb);
  1793. lcparams.mem_buffer = NULL;
  1794. lcparams.no_alloc = false;
  1795. model.ctx = ggml_init(lcparams);
  1796. int n_tokens = model.hparams.n_ctx;
  1797. int n_vocab = model.hparams.n_vocab;
  1798. int n_batch = params.n_batch;
  1799. struct ggml_opt_context * opt = (struct ggml_opt_context *) alloca(sizeof(struct ggml_opt_context));
  1800. memset(opt, 0, sizeof(struct ggml_opt_context));
  1801. struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
  1802. struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
  1803. opt_params_adam.print_forward_graph = false;
  1804. opt_params_adam.print_backward_graph = false;
  1805. opt_params_adam.n_threads = params.n_threads;
  1806. opt_params_adam.past = params.opt_past;
  1807. opt_params_adam.delta = params.opt_delta;
  1808. opt_params_adam.max_no_improvement = params.opt_max_no_improvement;
  1809. opt_params_adam.adam.n_iter = params.adam_n_iter;
  1810. opt_params_adam.adam.sched = 1.0f;
  1811. opt_params_adam.adam.alpha = params.adam_alpha;
  1812. opt_params_adam.adam.decay = params.adam_decay;
  1813. opt_params_adam.adam.decay_min_ndim = params.adam_decay_min_ndim;
  1814. opt_params_adam.adam.beta1 = params.adam_beta1;
  1815. opt_params_adam.adam.beta2 = params.adam_beta2;
  1816. opt_params_adam.adam.gclip = params.adam_gclip;
  1817. opt_params_adam.adam.eps_f = params.adam_eps_f;
  1818. opt_params_lbfgs.print_forward_graph = false;
  1819. opt_params_lbfgs.print_backward_graph = false;
  1820. opt_params_lbfgs.n_threads = params.n_threads;
  1821. opt_params_adam.past = params.opt_past;
  1822. opt_params_adam.delta = params.opt_delta;
  1823. opt_params_adam.max_no_improvement = params.opt_max_no_improvement;
  1824. opt_params_lbfgs.lbfgs.n_iter = params.lbfgs_n_iter;
  1825. opt->ctx = model.ctx;
  1826. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  1827. printf("%s: init model\n", __func__);
  1828. bool existed = load_checkpoint_file(params.fn_checkpoint_in, &model, opt);
  1829. if (!existed) {
  1830. init_model(&model);
  1831. }
  1832. set_param_model(&model);
  1833. opt->params = params.use_adam ? opt_params_adam : opt_params_lbfgs;
  1834. opt->iter = model.train_its;
  1835. printf("%s: opt iter %d\n", __func__, opt->iter);
  1836. bool from_scratch = !existed;
  1837. if (from_scratch) {
  1838. randomize_model(&model, params.seed, 0.0f, 1.0f, -1.0f, +1.0f);
  1839. }
  1840. printf("used_mem model: %zu bytes\n", ggml_used_mem(model.ctx));
  1841. // ggml_print_tensor_objects(model.ctx);
  1842. // TODO: use std::vector<uint8_t> intead of "new"
  1843. size_t compute_size = 1024ll*1024ll*1024ll*((size_t) params.mem_compute_gb);
  1844. uint8_t * compute_addr = new uint8_t[compute_size];
  1845. size_t size_buf_0 = 1024ll*1024ll*1024ll*((size_t) params.mem_compute0_gb);
  1846. uint8_t * compute_buf_0 = new uint8_t[size_buf_0];
  1847. ggml_allocr * alloc = NULL;
  1848. if (params.use_alloc) {
  1849. static const size_t tensor_alignment = 32;
  1850. alloc = ggml_allocr_new(compute_buf_0, size_buf_0, tensor_alignment);
  1851. }
  1852. GGML_ASSERT(n_tokens < (int) train_tokens.size());
  1853. std::vector<int> train_samples;
  1854. train_samples.push_back(0);
  1855. for (int i = 1; i < (int) train_tokens.size() - n_tokens; ++i) {
  1856. if (!params.samples_start_after_nl || (train_tokens[i-1] == llama_token_nl(lctx))) {
  1857. train_samples.push_back(i);
  1858. }
  1859. }
  1860. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  1861. for (int i = 0; i < (int) train_samples.size(); ++i) {
  1862. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  1863. }
  1864. printf("%s: begin training\n", __func__);
  1865. struct opt_callback_data opt_cb_data;
  1866. opt_cb_data.params = &params;
  1867. opt_cb_data.opt = opt;
  1868. opt_cb_data.lctx = lctx;
  1869. opt_cb_data.tokens_data = train_tokens.data();
  1870. opt_cb_data.tokens_size = train_tokens.size();
  1871. opt_cb_data.samples_data = train_samples.data();
  1872. opt_cb_data.samples_size = train_samples.size();
  1873. opt_cb_data.shuffle_countdown = train_samples.size();
  1874. opt_cb_data.tokens_input = NULL;
  1875. opt_cb_data.target_logits = NULL;
  1876. opt_cb_data.target_probs = NULL;
  1877. int64_t t0 = ggml_time_ms();
  1878. for (int ex = 0; ex < params.n_examples; ++ex) {
  1879. if (ex*n_batch >= (int) train_samples.size()) {
  1880. shuffle_ints(train_samples.data(), train_samples.data() + train_samples.size());
  1881. for (int i = 0; i < (int) train_samples.size(); ++i) {
  1882. GGML_ASSERT(train_samples[i]+n_tokens-1 < (int) train_tokens.size());
  1883. }
  1884. }
  1885. struct ggml_init_params cparams = {
  1886. compute_size, // mem_size
  1887. compute_addr, // mem_buffer
  1888. false, // no_alloc
  1889. };
  1890. struct ggml_context * ctx0 = ggml_init(cparams);
  1891. ggml_set_no_alloc(ctx0, false);
  1892. // don't use alloc for input tensors, so we can safely fill them with data
  1893. //struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1894. //struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1895. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1896. struct ggml_tensor * target_logits = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1897. struct ggml_tensor * target_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1898. ggml_set_no_alloc(ctx0, (alloc != NULL));
  1899. if (alloc) {
  1900. ggml_allocr_reset(alloc);
  1901. }
  1902. opt_cb_data.tokens_input = tokens_input;
  1903. opt_cb_data.target_logits = target_logits;
  1904. opt_cb_data.target_probs = target_probs;
  1905. int n_past = 0;
  1906. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  1907. struct ggml_cgraph * gb = ggml_new_graph(ctx0);
  1908. struct ggml_cgraph * gb_tmp = params.use_checkpointing
  1909. ? ggml_new_graph(ctx0)
  1910. : NULL;
  1911. GGML_ASSERT(n_past == 0);
  1912. struct ggml_tensor * loss = NULL;
  1913. struct ggml_tensor * logits = NULL;
  1914. loss = llama_build_train_graphs(
  1915. &model, alloc, ctx0,
  1916. gf, gb, gb_tmp,
  1917. &logits, tokens_input, target_probs,
  1918. n_tokens, n_batch,
  1919. params.use_flash,
  1920. params.use_checkpointing
  1921. );
  1922. size_t used_mem_before_opt = ggml_used_mem(ctx0);
  1923. opt->params.adam.sched = (opt->iter < params.warmup)
  1924. ? (float) opt->iter / (float) params.warmup
  1925. : cosine_decay_restart(
  1926. params.cos_decay_steps,
  1927. params.cos_decay_min,
  1928. opt->iter - params.warmup,
  1929. params.cos_decay_restart,
  1930. params.enable_restart);
  1931. float min_sched = params.adam_min_alpha / params.adam_alpha;
  1932. opt->params.adam.sched = min_sched + opt->params.adam.sched * (1.0f - min_sched);
  1933. printf("%s: opt->params.adam.sched %.5f\n", __func__, opt->params.adam.sched);
  1934. ggml_opt_resume_g(ctx0, opt, loss, gf, gb, &opt_callback, (void *) &opt_cb_data);
  1935. size_t used_mem_after_opt = ggml_used_mem(ctx0);
  1936. int n_iter = params.use_adam ? params.adam_n_iter : params.lbfgs_n_iter;
  1937. model.train_its = opt->iter;
  1938. model.train_samples += n_batch * n_iter;
  1939. model.train_tokens += n_batch * n_tokens * n_iter;
  1940. if (params.print_info_interval > 0 && ex % params.print_info_interval == 0) {
  1941. printf("Example %d, opt iter %d\n", ex, opt->iter);
  1942. printf("error_before_opt: %.6f\n", opt->loss_before);
  1943. printf("error_after_opt: %.6f\n", opt->loss_after);
  1944. printf("used_mem_before_opt: %zu bytes\n", used_mem_before_opt);
  1945. printf("used_mem_after_opt: %zu bytes\n", used_mem_after_opt);
  1946. }
  1947. ggml_free(ctx0);
  1948. }
  1949. int64_t t1 = ggml_time_ms();
  1950. int64_t d = t1-t0;
  1951. double dd = (double) d * 1e-3;
  1952. printf("%s: total training time=%f seconds\n", __func__, dd);
  1953. if (params.n_examples > 0) {
  1954. save_checkpoint_file(params.fn_checkpoint_out, params.fn_vocab_model, &model, opt);
  1955. }
  1956. if (strlen(params.fn_model_out) > 0) {
  1957. save_llama_model_file(params.fn_model_out, params.fn_vocab_model, &model);
  1958. }
  1959. if (alloc) {
  1960. ggml_allocr_free(alloc);
  1961. }
  1962. delete[] compute_addr;
  1963. delete[] compute_buf_0;
  1964. ggml_free(model.ctx);
  1965. llama_free(lctx);
  1966. llama_free_model(lmodel);
  1967. return 0;
  1968. }