train-text-from-scratch.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. #include "ggml.h"
  2. #include "ggml-alloc.h"
  3. #include "common.h"
  4. #include "train.h"
  5. #include "llama.h"
  6. #include <unordered_map>
  7. #include <vector>
  8. #include <cassert>
  9. #include <climits>
  10. #include <cstring>
  11. #include <cstdarg>
  12. #include <ctime>
  13. #include <random>
  14. #include <stdexcept>
  15. #include <algorithm>
  16. #include <string>
  17. #if defined(_MSC_VER)
  18. #pragma warning(disable: 4244 4267) // possible loss of data
  19. #endif
  20. static const size_t tensor_alignment = 32;
  21. struct my_llama_hparams {
  22. uint32_t n_vocab = 32000;
  23. uint32_t n_ctx = 512;
  24. uint32_t n_embd = 4096;
  25. uint32_t n_head = 32;
  26. uint32_t n_layer = 32;
  27. uint32_t n_rot = 64;
  28. uint32_t n_ff = 11008;
  29. // float f_norm_eps = 1e-5f; // falcon
  30. float f_norm_rms_eps = 1e-5f; // llama
  31. float rope_freq_base = 10000.0f;
  32. float rope_freq_scale = 1.0f;
  33. };
  34. struct my_llama_layer {
  35. // normalization
  36. struct ggml_tensor * attention_norm;
  37. // attention
  38. struct ggml_tensor * wq;
  39. struct ggml_tensor * wk;
  40. struct ggml_tensor * wv;
  41. struct ggml_tensor * wo;
  42. // normalization
  43. struct ggml_tensor * ffn_norm;
  44. // ff
  45. struct ggml_tensor * w1;
  46. struct ggml_tensor * w2;
  47. struct ggml_tensor * w3;
  48. };
  49. struct my_llama_model {
  50. struct ggml_context * ctx = NULL;
  51. std::vector<uint8_t> data;
  52. my_llama_hparams hparams;
  53. struct ggml_tensor * tok_embeddings;
  54. struct ggml_tensor * norm;
  55. struct ggml_tensor * output;
  56. std::vector<my_llama_layer> layers;
  57. };
  58. // gguf constants (sync with gguf.py)
  59. static const char * LLM_KV_TRAINING_TYPE_TRAIN_MODEL = "train_model";
  60. static const char * LLM_KV_TRAINING_TYPE = "training.type";
  61. static const char * LLM_KV_GENERAL_ARCHITECTURE = "general.architecture";
  62. static const char * LLM_KV_GENERAL_FILE_TYPE = "general.file_type";
  63. static const char * LLM_KV_CONTEXT_LENGTH = "%s.context_length";
  64. static const char * LLM_KV_EMBEDDING_LENGTH = "%s.embedding_length";
  65. static const char * LLM_KV_BLOCK_COUNT = "%s.block_count";
  66. static const char * LLM_KV_FEED_FORWARD_LENGTH = "%s.feed_forward_length";
  67. static const char * LLM_KV_ATTENTION_HEAD_COUNT = "%s.attention.head_count";
  68. static const char * LLM_KV_ATTENTION_LAYERNORM_RMS_EPS = "%s.attention.layer_norm_rms_epsilon";
  69. static const char * LLM_KV_ROPE_DIMENSION_COUNT = "%s.rope.dimension_count";
  70. static const char * LLM_KV_ROPE_FREQ_BASE = "%s.rope.freq_base"; // TODO load in llama.cpp
  71. static const char * LLM_KV_ROPE_SCALE_LINEAR = "%s.rope.scale_linear";
  72. static const char * LLM_KV_TOKENIZER_MODEL = "tokenizer.ggml.model";
  73. static const char * LLM_KV_TOKENIZER_LIST = "tokenizer.ggml.tokens";
  74. static const char * LLM_KV_TOKENIZER_TOKEN_TYPE = "tokenizer.ggml.token_type";
  75. static const char * LLM_KV_TOKENIZER_SCORES = "tokenizer.ggml.scores";
  76. static const char * LLM_KV_TOKENIZER_MERGES = "tokenizer.ggml.merges";
  77. static const char * LLM_KV_TOKENIZER_BOS_ID = "tokenizer.ggml.bos_token_id";
  78. static const char * LLM_KV_TOKENIZER_EOS_ID = "tokenizer.ggml.eos_token_id";
  79. static const char * LLM_KV_TOKENIZER_UNK_ID = "tokenizer.ggml.unknown_token_id";
  80. static const char * LLM_KV_TOKENIZER_SEP_ID = "tokenizer.ggml.seperator_token_id";
  81. static const char * LLM_KV_TOKENIZER_PAD_ID = "tokenizer.ggml.padding_token_id";
  82. static const char * LLM_TENSOR_TOKEN_EMBD = "token_embd";
  83. static const char * LLM_TENSOR_OUTPUT_NORM = "output_norm";
  84. static const char * LLM_TENSOR_OUTPUT = "output";
  85. static const char * LLM_TENSOR_ATTN_NORM = "blk.%d.attn_norm";
  86. static const char * LLM_TENSOR_ATTN_Q = "blk.%d.attn_q";
  87. static const char * LLM_TENSOR_ATTN_K = "blk.%d.attn_k";
  88. static const char * LLM_TENSOR_ATTN_V = "blk.%d.attn_v";
  89. static const char * LLM_TENSOR_ATTN_OUT = "blk.%d.attn_output";
  90. static const char * LLM_TENSOR_FFN_NORM = "blk.%d.ffn_norm";
  91. static const char * LLM_TENSOR_FFN_GATE = "blk.%d.ffn_gate";
  92. static const char * LLM_TENSOR_FFN_DOWN = "blk.%d.ffn_down";
  93. static const char * LLM_TENSOR_FFN_UP = "blk.%d.ffn_up";
  94. static void print_params(struct my_llama_hparams * params) {
  95. printf("%s: n_vocab: %d\n", __func__, params->n_vocab);
  96. printf("%s: n_ctx: %d\n", __func__, params->n_ctx);
  97. printf("%s: n_embd: %d\n", __func__, params->n_embd);
  98. printf("%s: n_head: %d\n", __func__, params->n_head);
  99. printf("%s: n_ff: %d\n", __func__, params->n_ff);
  100. printf("%s: n_layer: %d\n", __func__, params->n_layer);
  101. printf("%s: n_rot: %d\n", __func__, params->n_rot);
  102. }
  103. static void set_param_model(struct my_llama_model * model) {
  104. const auto& hparams = model->hparams;
  105. const uint32_t n_layer = hparams.n_layer;
  106. struct ggml_context* ctx = model->ctx;
  107. ggml_set_param(ctx, model->tok_embeddings);
  108. ggml_set_param(ctx, model->norm);
  109. ggml_set_param(ctx, model->output);
  110. for (uint32_t i = 0; i < n_layer; ++i) {
  111. auto & layer = model->layers[i];
  112. ggml_set_param(ctx, layer.attention_norm);
  113. ggml_set_param(ctx, layer.wq);
  114. ggml_set_param(ctx, layer.wk);
  115. ggml_set_param(ctx, layer.wv);
  116. ggml_set_param(ctx, layer.wo);
  117. ggml_set_param(ctx, layer.ffn_norm);
  118. ggml_set_param(ctx, layer.w1);
  119. ggml_set_param(ctx, layer.w2);
  120. ggml_set_param(ctx, layer.w3);
  121. }
  122. }
  123. static void alloc_model(struct ggml_allocr * alloc, struct my_llama_model * model) {
  124. ggml_allocr_alloc(alloc, model->tok_embeddings);
  125. ggml_allocr_alloc(alloc, model->norm);
  126. ggml_allocr_alloc(alloc, model->output);
  127. for (uint32_t i = 0; i < model->layers.size(); ++i) {
  128. auto & layer = model->layers[i];
  129. ggml_allocr_alloc(alloc, layer.attention_norm);
  130. ggml_allocr_alloc(alloc, layer.wq);
  131. ggml_allocr_alloc(alloc, layer.wk);
  132. ggml_allocr_alloc(alloc, layer.wv);
  133. ggml_allocr_alloc(alloc, layer.wo);
  134. ggml_allocr_alloc(alloc, layer.ffn_norm);
  135. ggml_allocr_alloc(alloc, layer.w1);
  136. ggml_allocr_alloc(alloc, layer.w2);
  137. ggml_allocr_alloc(alloc, layer.w3);
  138. }
  139. ggml_allocr_alloc(alloc, model->tok_embeddings->grad);
  140. ggml_allocr_alloc(alloc, model->norm->grad);
  141. ggml_allocr_alloc(alloc, model->output->grad);
  142. for (uint32_t i = 0; i < model->layers.size(); ++i) {
  143. auto & layer = model->layers[i];
  144. ggml_allocr_alloc(alloc, layer.attention_norm->grad);
  145. ggml_allocr_alloc(alloc, layer.wq->grad);
  146. ggml_allocr_alloc(alloc, layer.wk->grad);
  147. ggml_allocr_alloc(alloc, layer.wv->grad);
  148. ggml_allocr_alloc(alloc, layer.wo->grad);
  149. ggml_allocr_alloc(alloc, layer.ffn_norm->grad);
  150. ggml_allocr_alloc(alloc, layer.w1->grad);
  151. ggml_allocr_alloc(alloc, layer.w2->grad);
  152. ggml_allocr_alloc(alloc, layer.w3->grad);
  153. }
  154. }
  155. static void init_model(struct my_llama_model * model) {
  156. const auto & hparams = model->hparams;
  157. const uint32_t n_embd = hparams.n_embd;
  158. const uint32_t n_layer = hparams.n_layer;
  159. const uint32_t n_vocab = hparams.n_vocab;
  160. const uint32_t n_ff = hparams.n_ff;
  161. std::vector<char> tn_buf;
  162. tn_buf.resize(GGML_MAX_NAME);
  163. auto tn = [&tn_buf](const char * key) -> const char * {
  164. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", key);
  165. return tn_buf.data();
  166. };
  167. auto tni = [&tn_buf](const char * key, int bid) -> const char * {
  168. snprintf(tn_buf.data(), tn_buf.size(), key, bid);
  169. std::string s = tn_buf.data();
  170. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", s.c_str());
  171. return tn_buf.data();
  172. };
  173. // context for model tensors without their data
  174. struct ggml_init_params ctx_model_params;
  175. ctx_model_params.mem_size = ggml_tensor_overhead()*2*(6 + n_layer*18);
  176. ctx_model_params.mem_buffer = NULL;
  177. ctx_model_params.no_alloc = true;
  178. struct ggml_context * ctx = ggml_init(ctx_model_params);
  179. model->ctx = ctx;
  180. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  181. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  182. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  183. ggml_set_name(model->tok_embeddings, tn(LLM_TENSOR_TOKEN_EMBD));
  184. ggml_set_name(model->norm, tn(LLM_TENSOR_OUTPUT_NORM));
  185. ggml_set_name(model->output, tn(LLM_TENSOR_OUTPUT));
  186. model->layers.resize(n_layer);
  187. for (uint32_t i = 0; i < n_layer; ++i) {
  188. auto & layer = model->layers[i];
  189. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  190. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  191. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  192. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  193. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  194. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  195. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  196. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd);
  197. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  198. ggml_set_name(layer.attention_norm, tni(LLM_TENSOR_ATTN_NORM, i));
  199. ggml_set_name(layer.wq, tni(LLM_TENSOR_ATTN_Q, i));
  200. ggml_set_name(layer.wk, tni(LLM_TENSOR_ATTN_K, i));
  201. ggml_set_name(layer.wv, tni(LLM_TENSOR_ATTN_V, i));
  202. ggml_set_name(layer.wo, tni(LLM_TENSOR_ATTN_OUT, i));
  203. ggml_set_name(layer.ffn_norm, tni(LLM_TENSOR_FFN_NORM, i));
  204. ggml_set_name(layer.w1, tni(LLM_TENSOR_FFN_GATE, i));
  205. ggml_set_name(layer.w2, tni(LLM_TENSOR_FFN_DOWN, i));
  206. ggml_set_name(layer.w3, tni(LLM_TENSOR_FFN_UP, i));
  207. }
  208. set_param_model(model);
  209. // measure data size
  210. size_t size = 0;
  211. for (struct ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  212. size += GGML_PAD(ggml_nbytes(t), tensor_alignment);
  213. }
  214. // allocate data
  215. struct ggml_allocr * alloc = NULL;
  216. model->data.resize(size + tensor_alignment);
  217. alloc = ggml_allocr_new(model->data.data(), model->data.size(), tensor_alignment);
  218. alloc_model(alloc, model);
  219. ggml_allocr_free(alloc);
  220. }
  221. static void randomize_model(struct my_llama_model * model, int seed, float mean, float std, float min, float max) {
  222. const auto & hparams = model->hparams;
  223. const uint32_t n_layer = hparams.n_layer;
  224. struct random_normal_distribution * rnd = init_random_normal_distribution(seed, mean, std, min, max);
  225. randomize_tensor_normal(model->tok_embeddings, rnd);
  226. randomize_tensor_normal(model->norm, rnd);
  227. randomize_tensor_normal(model->output, rnd);
  228. for (uint32_t i = 0; i < n_layer; ++i) {
  229. auto & layer = model->layers[i];
  230. randomize_tensor_normal(layer.attention_norm, rnd);
  231. randomize_tensor_normal(layer.wq, rnd);
  232. randomize_tensor_normal(layer.wk, rnd);
  233. randomize_tensor_normal(layer.wv, rnd);
  234. randomize_tensor_normal(layer.wo, rnd);
  235. randomize_tensor_normal(layer.ffn_norm, rnd);
  236. randomize_tensor_normal(layer.w1, rnd);
  237. randomize_tensor_normal(layer.w2, rnd);
  238. randomize_tensor_normal(layer.w3, rnd);
  239. }
  240. free_random_normal_distribution(rnd);
  241. }
  242. static struct ggml_tensor * llama_build_train_graphs(
  243. struct my_llama_model * model,
  244. struct ggml_allocr * alloc,
  245. struct ggml_context * ctx,
  246. struct ggml_cgraph * gf,
  247. struct ggml_cgraph * gb,
  248. struct ggml_cgraph * gb_tmp,
  249. struct ggml_tensor * * logits,
  250. struct ggml_tensor * tokens_input,
  251. struct ggml_tensor * targets,
  252. const int n_tokens,
  253. const int n_batch,
  254. const bool enable_flash_attn,
  255. const bool enable_checkpointing) {
  256. ggml_set_scratch(ctx, { 0, 0, nullptr, });
  257. const int n_past = 0;
  258. const int N = n_tokens;
  259. const auto & hparams = model->hparams;
  260. const int n_ctx = hparams.n_ctx;
  261. const int n_vocab = hparams.n_vocab;
  262. const int n_embd = hparams.n_embd;
  263. const int n_layer = hparams.n_layer;
  264. const int n_head = hparams.n_head;
  265. const int n_rot = hparams.n_rot;
  266. const int n_ff = hparams.n_ff;
  267. const float f_norm_rms_eps = hparams.f_norm_rms_eps;
  268. const float rope_freq_base = hparams.rope_freq_base;
  269. const float rope_freq_scale = hparams.rope_freq_scale;
  270. auto set_name = [](struct ggml_tensor * t, const char * n) {
  271. ggml_set_name(t, n);
  272. if (t->grad) {
  273. ggml_format_name(t->grad, "%s->grad", n);
  274. }
  275. };
  276. // KQ_pos - contains the positions
  277. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
  278. ggml_allocr_alloc(alloc, KQ_pos);
  279. if (!ggml_allocr_is_measure(alloc)) {
  280. int * data = (int *) KQ_pos->data;
  281. for (int i = 0; i < N; ++i) {
  282. data[i] = n_past + i;
  283. }
  284. }
  285. // rope has so much parameters that we make a custom function for it
  286. auto rope = [ctx, KQ_pos, n_rot, n_ctx, rope_freq_base, rope_freq_scale]
  287. (struct ggml_tensor * t) -> struct ggml_tensor * {
  288. // not capturing these, to silcence warnings
  289. const int rope_mode = 0;
  290. return ggml_rope_custom(
  291. ctx, t, KQ_pos, n_rot, rope_mode, n_ctx, 0, rope_freq_base, rope_freq_scale, 0.0f, 1.0f, 0.0f, 0.0f
  292. );
  293. };
  294. set_name(tokens_input, "tokens_input");
  295. set_name(targets, "targets");
  296. GGML_ASSERT(tokens_input->type == GGML_TYPE_I32);
  297. struct ggml_tensor * t00 = ggml_reshape_1d(ctx, tokens_input, N*n_batch); set_name(t00, "t00"); assert_shape_1d(t00, N*n_batch);
  298. 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);
  299. struct ggml_tensor * cur = t01;
  300. std::vector<struct ggml_tensor *> checkpoints;
  301. checkpoints.push_back(tokens_input);
  302. checkpoints.push_back(targets);
  303. checkpoints.push_back(t00);
  304. checkpoints.push_back(t01);
  305. const float kv_scale = 1.0f/sqrtf(float(n_embd)/n_head);
  306. for (int il = 0; il < n_layer; ++il) {
  307. struct my_llama_layer & layer = model->layers[il];
  308. 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);
  309. struct ggml_tensor * t03 = ggml_repeat (ctx, layer.attention_norm, t02); set_name(t03, "t03"); assert_shape_2d(t03, n_embd, N*n_batch);
  310. struct ggml_tensor * t04 = ggml_mul (ctx, t03, t02); set_name(t04, "t04"); assert_shape_2d(t04, n_embd, N*n_batch);
  311. struct ggml_tensor * t05 = ggml_mul_mat (ctx, layer.wq, t04); set_name(t05, "t05"); assert_shape_2d(t05, n_embd, N*n_batch);
  312. 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);
  313. struct ggml_tensor * t07 = rope (t06); set_name(t07, "t07"); assert_shape_4d(t07, n_embd/n_head, n_head, N, n_batch);
  314. struct ggml_tensor * t08 = ggml_mul_mat (ctx, layer.wk, t04); set_name(t08, "t08"); assert_shape_2d(t08, n_embd, N*n_batch);
  315. 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);
  316. struct ggml_tensor * t10 = rope (t09); set_name(t10, "t10"); assert_shape_4d(t10, n_embd/n_head, n_head, N, n_batch);
  317. struct ggml_tensor * t11 = ggml_mul_mat (ctx, t04, layer.wv); set_name(t11, "t11"); assert_shape_2d(t11, N*n_batch, n_embd);
  318. 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);
  319. 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);
  320. 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);
  321. 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);
  322. struct ggml_tensor * t16;
  323. if (enable_flash_attn) {
  324. 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);
  325. } else {
  326. 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);
  327. 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);
  328. 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);
  329. 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);
  330. 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);
  331. }
  332. 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);
  333. 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);
  334. 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);
  335. struct ggml_tensor * t20 = ggml_mul_mat (ctx, layer.wo, t19); set_name(t20, "t20"); assert_shape_2d(t20, n_embd, N*n_batch);
  336. struct ggml_tensor * t21 = ggml_add (ctx, t20, cur); set_name(t21, "t21"); assert_shape_2d(t21, n_embd, N*n_batch);
  337. 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);
  338. struct ggml_tensor * t23 = ggml_repeat (ctx, layer.ffn_norm, t22); set_name(t23, "t23"); assert_shape_2d(t23, n_embd, N*n_batch);
  339. struct ggml_tensor * t24 = ggml_mul (ctx, t23, t22); set_name(t24, "t24"); assert_shape_2d(t24, n_embd, N*n_batch);
  340. struct ggml_tensor * t25 = ggml_mul_mat (ctx, layer.w3, t24); set_name(t25, "t25"); assert_shape_2d(t25, n_ff, N*n_batch);
  341. struct ggml_tensor * t26 = ggml_mul_mat (ctx, layer.w1, t24); set_name(t26, "t26"); assert_shape_2d(t26, n_ff, N*n_batch);
  342. struct ggml_tensor * t27 = ggml_silu (ctx, t26); set_name(t27, "t27"); assert_shape_2d(t27, n_ff, N*n_batch);
  343. struct ggml_tensor * t28 = ggml_mul (ctx, t27, t25); set_name(t28, "t28"); assert_shape_2d(t28, n_ff, N*n_batch);
  344. struct ggml_tensor * t29 = ggml_mul_mat (ctx, layer.w2, t28); set_name(t29, "t29"); assert_shape_2d(t29, n_embd, N*n_batch);
  345. struct ggml_tensor * t30 = ggml_add (ctx, t29, t21); set_name(t30, "t30"); assert_shape_2d(t30, n_embd, N*n_batch);
  346. cur = t30;
  347. checkpoints.push_back(cur);
  348. }
  349. 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);
  350. struct ggml_tensor * t32 = ggml_repeat (ctx, model->norm, t31); set_name(t32, "t32"); assert_shape_2d(t32, n_embd, N*n_batch);
  351. struct ggml_tensor * t33 = ggml_mul (ctx, t32, t31); set_name(t33, "t33"); assert_shape_2d(t33, n_embd, N*n_batch);
  352. struct ggml_tensor * t34 = ggml_mul_mat (ctx, model->output, t33); set_name(t34, "t34"); assert_shape_2d(t34, n_vocab, N*n_batch);
  353. 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);
  354. struct ggml_tensor * t36 = ggml_cross_entropy_loss(ctx, t35, targets); set_name(t36, "t36"); assert_shape_1d(t36, 1);
  355. checkpoints.push_back(t31);
  356. checkpoints.push_back(t32);
  357. checkpoints.push_back(t33);
  358. checkpoints.push_back(t34);
  359. checkpoints.push_back(t35);
  360. checkpoints.push_back(t36);
  361. ggml_build_forward_expand(gf, t36);
  362. if (enable_checkpointing) {
  363. ggml_build_backward_gradient_checkpointing(ctx, gf, gb, gb_tmp, checkpoints.data(), (int) checkpoints.size());
  364. } else {
  365. ggml_graph_cpy(gf, gb);
  366. ggml_build_backward_expand(ctx, gf, gb, true);
  367. }
  368. if (alloc) {
  369. // make sure some tensors are not reallocated by inserting new temporary nodes depending on them
  370. int n_leafs_before = gb->n_leafs;
  371. int n_nodes_before = gb->n_nodes;
  372. // output tensors
  373. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t35, 1.0f));
  374. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36, 1.0f));
  375. // input gradient
  376. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, t36->grad, 1.0f));
  377. // KQ_pos
  378. ggml_build_forward_expand(gb, ggml_scale_inplace(ctx, KQ_pos, 1.0f));
  379. GGML_ASSERT(t36->grad->data == NULL && t36->grad->view_src == NULL);
  380. ggml_allocr_alloc(alloc, t36->grad);
  381. // allocating checkpoints in one block to reduce memory fragmentation
  382. // note: they will be freed in reverse order
  383. for (int i = 0; i < (int) checkpoints.size(); ++i) {
  384. if (checkpoints[i]->data == NULL && checkpoints[i]->view_src == NULL) {
  385. ggml_allocr_alloc(alloc, checkpoints[i]);
  386. }
  387. }
  388. //int n_leafs_after = gb->n_leafs;
  389. //int n_nodes_after = gb->n_nodes;
  390. ggml_allocr_alloc_graph(alloc, gb);
  391. // remove the additional nodes and leafs
  392. for (int i = n_leafs_before; i < gb->n_leafs; ++i) {
  393. gb->leafs[i] = NULL;
  394. }
  395. for (int i = n_nodes_before; i < gb->n_nodes; ++i) {
  396. gb->nodes[i] = NULL;
  397. }
  398. gb->n_leafs = n_leafs_before;
  399. gb->n_nodes = n_nodes_before;
  400. }
  401. *logits = t35;
  402. return t36;
  403. }
  404. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  405. do { \
  406. const std::string skey(key); \
  407. const int kid = gguf_find_key(ctx, skey.c_str()); \
  408. if (kid >= 0) { \
  409. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  410. if (ktype != (type)) { \
  411. die_fmt("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype)); \
  412. } \
  413. (dst) = func(ctx, kid); \
  414. } else if (req) { \
  415. die_fmt("key not found in model: %s", skey.c_str()); \
  416. } \
  417. } while (0)
  418. static void load_llama_model_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model) {
  419. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  420. std::string arch;
  421. std::vector<char> keybuf;
  422. keybuf.resize(512);
  423. auto kv = [&arch, &keybuf](const char * key) -> const char * {
  424. snprintf(keybuf.data(), keybuf.size(), key, arch.c_str());
  425. return keybuf.data();
  426. };
  427. std::vector<char> tn_buf;
  428. tn_buf.resize(GGML_MAX_NAME);
  429. auto tn = [&tn_buf](const char * key) -> const char * {
  430. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", key);
  431. return tn_buf.data();
  432. };
  433. auto tni = [&tn_buf](const char * key, int bid) -> const char * {
  434. snprintf(tn_buf.data(), tn_buf.size(), key, bid);
  435. std::string s = tn_buf.data();
  436. snprintf(tn_buf.data(), tn_buf.size(), "%s.weight", s.c_str());
  437. return tn_buf.data();
  438. };
  439. GGUF_GET_KEY(fctx, arch, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_GENERAL_ARCHITECTURE);
  440. GGML_ASSERT(arch == "llama");
  441. uint32_t ftype_u;
  442. GGUF_GET_KEY(fctx, ftype_u, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_GENERAL_FILE_TYPE);
  443. GGML_ASSERT((enum llama_ftype) ftype_u == LLAMA_FTYPE_ALL_F32);
  444. // n_ctx was not saved in earlier checkpoint file versions, so we make it optional here
  445. GGUF_GET_KEY(fctx, model->hparams.n_ctx, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_CONTEXT_LENGTH));
  446. GGUF_GET_KEY(fctx, model->hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  447. GGUF_GET_KEY(fctx, model->hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  448. GGUF_GET_KEY(fctx, model->hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  449. GGUF_GET_KEY(fctx, model->hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  450. model->hparams.n_rot = model->hparams.n_embd / model->hparams.n_head;
  451. GGUF_GET_KEY(fctx, model->hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  452. float rope_freq_scale = 1.0f;
  453. 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));
  454. GGUF_GET_KEY(fctx, model->hparams.rope_freq_base, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  455. GGUF_GET_KEY(fctx, rope_freq_scale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  456. if (rope_freq_scale != 1.0f) {
  457. model->hparams.rope_freq_scale = 1.0f / rope_freq_scale;
  458. }
  459. init_model(model);
  460. copy_tensor_by_name(model->tok_embeddings, f_ggml_ctx, tn(LLM_TENSOR_TOKEN_EMBD));
  461. copy_tensor_by_name(model->norm, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT_NORM));
  462. copy_tensor_by_name(model->output, f_ggml_ctx, tn(LLM_TENSOR_OUTPUT));
  463. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  464. auto & layer = model->layers[i];
  465. copy_tensor_by_name(layer.attention_norm, f_ggml_ctx, tni(LLM_TENSOR_ATTN_NORM, i));
  466. copy_tensor_by_name(layer.wq, f_ggml_ctx, tni(LLM_TENSOR_ATTN_Q, i));
  467. copy_tensor_by_name(layer.wk, f_ggml_ctx, tni(LLM_TENSOR_ATTN_K, i));
  468. copy_tensor_by_name(layer.wv, f_ggml_ctx, tni(LLM_TENSOR_ATTN_V, i));
  469. copy_tensor_by_name(layer.wo, f_ggml_ctx, tni(LLM_TENSOR_ATTN_OUT, i));
  470. copy_tensor_by_name(layer.ffn_norm, f_ggml_ctx, tni(LLM_TENSOR_FFN_NORM, i));
  471. copy_tensor_by_name(layer.w1, f_ggml_ctx, tni(LLM_TENSOR_FFN_GATE, i));
  472. copy_tensor_by_name(layer.w2, f_ggml_ctx, tni(LLM_TENSOR_FFN_DOWN, i));
  473. copy_tensor_by_name(layer.w3, f_ggml_ctx, tni(LLM_TENSOR_FFN_UP, i));
  474. }
  475. }
  476. static void save_llama_model_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model) {
  477. const char * arch = "llama";
  478. enum llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  479. std::vector<char> keybuf;
  480. keybuf.resize(512);
  481. auto kv = [arch, &keybuf](const char * key) -> const char * {
  482. snprintf(keybuf.data(), keybuf.size(), key, arch);
  483. return keybuf.data();
  484. };
  485. // set arch
  486. gguf_set_val_str(fctx, LLM_KV_GENERAL_ARCHITECTURE, arch);
  487. gguf_set_val_u32(fctx, LLM_KV_GENERAL_FILE_TYPE, ftype);
  488. // set hparams
  489. gguf_set_val_u32(fctx, kv(LLM_KV_CONTEXT_LENGTH), model->hparams.n_ctx );
  490. gguf_set_val_u32(fctx, kv(LLM_KV_EMBEDDING_LENGTH), model->hparams.n_embd );
  491. gguf_set_val_u32(fctx, kv(LLM_KV_FEED_FORWARD_LENGTH), model->hparams.n_ff );
  492. gguf_set_val_u32(fctx, kv(LLM_KV_ATTENTION_HEAD_COUNT), model->hparams.n_head );
  493. gguf_set_val_u32(fctx, kv(LLM_KV_BLOCK_COUNT), model->hparams.n_layer );
  494. gguf_set_val_u32(fctx, kv(LLM_KV_ROPE_DIMENSION_COUNT), model->hparams.n_rot );
  495. gguf_set_val_f32(fctx, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS), model->hparams.f_norm_rms_eps );
  496. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_FREQ_BASE), model->hparams.rope_freq_base ); // TODO load in llama.cpp
  497. gguf_set_val_f32(fctx, kv(LLM_KV_ROPE_SCALE_LINEAR), 1.0f / model->hparams.rope_freq_scale );
  498. // set vocab by copying from vocab_model gguf file
  499. {
  500. struct gguf_init_params params = {
  501. /*.no_alloc = */ false,
  502. /*.ctx = */ NULL,
  503. };
  504. struct gguf_context * vctx = gguf_init_from_file(fn_vocab_model, params);
  505. const int token_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_LIST));
  506. if (token_idx == -1) {
  507. die("cannot find tokenizer vocab in model file");
  508. }
  509. const uint32_t n_vocab = gguf_get_arr_n(vctx, token_idx);
  510. const int score_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_SCORES));
  511. if (score_idx == -1) {
  512. die("cannot find tokenizer scores in model file");
  513. }
  514. const float * scores = (const float * ) gguf_get_arr_data(vctx, score_idx);
  515. const int toktype_idx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE));
  516. if (toktype_idx == -1) {
  517. die("cannot find token type list in GGUF file");
  518. }
  519. const int * toktypes = (const int * ) gguf_get_arr_data(vctx, toktype_idx);
  520. std::string tokenizer_name;
  521. GGUF_GET_KEY(vctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  522. gguf_set_val_str(fctx, kv(LLM_KV_TOKENIZER_MODEL), tokenizer_name.c_str());
  523. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_SCORES), GGUF_TYPE_FLOAT32, scores, n_vocab);
  524. gguf_set_arr_data(fctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE), GGUF_TYPE_INT32, toktypes, n_vocab);
  525. int32_t special_bos_id = 1;
  526. int32_t special_eos_id = 2;
  527. int32_t special_unk_id = 0;
  528. int32_t special_sep_id = -1;
  529. int32_t special_pad_id = -1;
  530. if (tokenizer_name == "llama") {
  531. // default special tokens
  532. special_bos_id = 1;
  533. special_eos_id = 2;
  534. special_unk_id = 0;
  535. special_sep_id = -1;
  536. special_pad_id = -1;
  537. } else if (tokenizer_name == "gpt2") {
  538. // read and copy bpe merges
  539. const int merges_keyidx = gguf_find_key(vctx, kv(LLM_KV_TOKENIZER_MERGES));
  540. if (merges_keyidx == -1) {
  541. die("cannot find tokenizer merges in model file");
  542. }
  543. const int n_merges = gguf_get_arr_n(vctx, merges_keyidx);
  544. std::vector<const char*> merges;
  545. merges.resize(n_merges);
  546. for (int i = 0; i < n_merges; i++) {
  547. merges[i] = gguf_get_arr_str(vctx, merges_keyidx, i);
  548. }
  549. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_MERGES), merges.data(), n_merges);
  550. // default special tokens
  551. special_bos_id = 11;
  552. special_eos_id = 11;
  553. special_unk_id = -1;
  554. special_sep_id = -1;
  555. special_pad_id = -1;
  556. } else {
  557. fprintf(stderr, "%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  558. fprintf(stderr, "%s: using default tokenizer: 'llama'", __func__);
  559. }
  560. std::vector<const char*> tokens;
  561. tokens.resize(n_vocab);
  562. for (uint32_t i = 0; i < n_vocab; i++) {
  563. tokens[i] = gguf_get_arr_str(vctx, token_idx, i);
  564. }
  565. gguf_set_arr_str(fctx, kv(LLM_KV_TOKENIZER_LIST), tokens.data(), n_vocab);
  566. GGUF_GET_KEY(vctx, special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  567. GGUF_GET_KEY(vctx, special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  568. GGUF_GET_KEY(vctx, special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  569. GGUF_GET_KEY(vctx, special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  570. GGUF_GET_KEY(vctx, special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  571. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_BOS_ID), special_bos_id);
  572. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_EOS_ID), special_eos_id);
  573. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_UNK_ID), special_unk_id);
  574. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_SEP_ID), special_sep_id);
  575. gguf_set_val_u32(fctx, kv(LLM_KV_TOKENIZER_PAD_ID), special_pad_id);
  576. gguf_free(vctx);
  577. }
  578. // add tensors
  579. gguf_add_tensor(fctx, model->tok_embeddings);
  580. gguf_add_tensor(fctx, model->norm);
  581. gguf_add_tensor(fctx, model->output);
  582. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  583. auto & layer = model->layers[i];
  584. gguf_add_tensor(fctx, layer.attention_norm);
  585. gguf_add_tensor(fctx, layer.wq);
  586. gguf_add_tensor(fctx, layer.wk);
  587. gguf_add_tensor(fctx, layer.wv);
  588. gguf_add_tensor(fctx, layer.wo);
  589. gguf_add_tensor(fctx, layer.ffn_norm);
  590. gguf_add_tensor(fctx, layer.w1);
  591. gguf_add_tensor(fctx, layer.w2);
  592. gguf_add_tensor(fctx, layer.w3);
  593. }
  594. }
  595. static void save_llama_model_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model) {
  596. printf("%s: saving to %s\n", __func__, filename);
  597. struct gguf_context * fctx = gguf_init_empty();
  598. save_llama_model_gguf(fctx, fn_vocab_model, model);
  599. // write file
  600. const bool only_meta = false;
  601. gguf_write_to_file(fctx, filename, only_meta);
  602. gguf_free(fctx);
  603. }
  604. static void load_checkpoint_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct my_llama_model * model, struct train_state * train) {
  605. load_llama_model_gguf(fctx, f_ggml_ctx, model);
  606. if (load_train_state_gguf(fctx, f_ggml_ctx, train)) {
  607. std::string train_type = LLM_KV_TRAINING_TYPE_TRAIN_MODEL;
  608. GGUF_GET_KEY(fctx, train_type, gguf_get_val_str, GGUF_TYPE_STRING, false, LLM_KV_TRAINING_TYPE);
  609. GGML_ASSERT(train_type == LLM_KV_TRAINING_TYPE_TRAIN_MODEL);
  610. } else {
  611. printf("%s: loaded llama model as checkpoint\n", __func__);
  612. }
  613. }
  614. static void save_checkpoint_gguf(struct gguf_context * fctx, const char * fn_vocab_model, struct my_llama_model * model, struct train_state * train) {
  615. gguf_set_val_str(fctx, LLM_KV_TRAINING_TYPE, LLM_KV_TRAINING_TYPE_TRAIN_MODEL);
  616. save_llama_model_gguf(fctx, fn_vocab_model, model);
  617. save_train_state_gguf(fctx, train);
  618. }
  619. static bool load_checkpoint_file(const char * filename, struct my_llama_model * model, struct train_state * train) {
  620. struct ggml_context * f_ggml_ctx;
  621. struct gguf_init_params params;
  622. params.no_alloc = false;
  623. params.ctx = &f_ggml_ctx;
  624. struct gguf_context * fctx = gguf_init_from_file(filename, params);
  625. if (fctx == NULL) {
  626. return false;
  627. }
  628. load_checkpoint_gguf(fctx, f_ggml_ctx, model, train);
  629. return true;
  630. }
  631. static void save_checkpoint_file(const char * filename, const char * fn_vocab_model, struct my_llama_model * model, struct train_state * train) {
  632. printf("%s: saving to %s\n", __func__, filename);
  633. struct gguf_context * fctx = gguf_init_empty();
  634. save_checkpoint_gguf(fctx, fn_vocab_model, model, train);
  635. // write file
  636. const bool only_meta = false;
  637. gguf_write_to_file(fctx, filename, only_meta);
  638. gguf_free(fctx);
  639. }
  640. struct train_params {
  641. struct train_params_common common;
  642. const char * fn_vocab_model;
  643. const char * fn_model_out;
  644. bool only_write_model;
  645. int n_ctx;
  646. int n_embd;
  647. int n_head;
  648. int n_layer;
  649. int n_ff;
  650. float f_norm_rms_eps;
  651. float rope_freq_base;
  652. float rope_freq_scale;
  653. };
  654. static struct train_params get_default_train_params() {
  655. struct train_params params;
  656. params.common = get_default_train_params_common();
  657. params.fn_vocab_model = "ggml-vic7b-uncensored-q4_0.bin";
  658. params.fn_model_out = "ggml-checkpoint-f32.bin";
  659. params.only_write_model = false;
  660. params.n_ctx = 128;
  661. params.n_embd = 256;
  662. params.n_head = 8;
  663. params.n_layer = 16;
  664. params.n_ff = 768;
  665. params.f_norm_rms_eps = 1e-5f;
  666. params.rope_freq_base = 10000.0f;
  667. params.rope_freq_scale = 1.0f;
  668. return params;
  669. }
  670. static void train_print_usage(int argc, char ** argv, const struct train_params * params) {
  671. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  672. fprintf(stderr, "\n");
  673. fprintf(stderr, "options:\n");
  674. fprintf(stderr, " -h, --help show this help message and exit\n");
  675. fprintf(stderr, " --vocab-model FNAME model path from which to load vocab (default '%s')\n", params->fn_vocab_model);
  676. fprintf(stderr, " --model-out FNAME path to save ggml model (default '%s')\n", params->fn_model_out);
  677. fprintf(stderr, " --only-write-model only save llama model, don't do any training. use this if you only want to convert a checkpoint to a model.\n");
  678. fprintf(stderr, " --embd N Embedding size used for new models (default %d)\n", params->n_embd);
  679. fprintf(stderr, " --ff N Feedforward size used for new models. (default %d)\n", params->n_ff);
  680. fprintf(stderr, " --head N Number of heads for new models (default %d)\n", params->n_head);
  681. fprintf(stderr, " --layer N Number of layers for new models (default %d)\n", params->n_layer);
  682. fprintf(stderr, " --norm-rms-eps F RMS-Norm epsilon value (default %f)\n", params->f_norm_rms_eps);
  683. fprintf(stderr, " --rope-freq-base F Frequency base for ROPE (default %f)\n", params->rope_freq_base);
  684. fprintf(stderr, " --rope-freq-scale F Frequency scale for ROPE (default %f)\n", params->rope_freq_scale);
  685. print_common_train_usage(argc, argv, &params->common);
  686. }
  687. static bool train_params_parse(int argc, char ** argv, struct train_params * params) {
  688. bool invalid_param = false;
  689. std::string arg;
  690. struct train_params default_params = get_default_train_params();
  691. const std::string arg_prefix = "--";
  692. for (int i = 1; i < argc; i++) {
  693. arg = argv[i];
  694. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  695. std::replace(arg.begin(), arg.end(), '_', '-');
  696. }
  697. if (consume_common_train_arg(argc, argv, &i, &params->common, &invalid_param)) {
  698. if (invalid_param) {
  699. break;
  700. } else if (params->common.print_usage) {
  701. train_print_usage(argc, argv, &default_params);
  702. exit(0);
  703. }
  704. } else if (arg == "--vocab-model") {
  705. if (++i >= argc) {
  706. invalid_param = true;
  707. break;
  708. }
  709. params->fn_vocab_model = argv[i];
  710. } else if (arg == "--model-out") {
  711. if (++i >= argc) {
  712. invalid_param = true;
  713. break;
  714. }
  715. params->fn_model_out = argv[i];
  716. } else if (arg == "--only-write-model") {
  717. params->only_write_model = true;
  718. } else if (arg == "--embd") {
  719. if (++i >= argc) {
  720. invalid_param = true;
  721. break;
  722. }
  723. params->n_embd = std::stoi(argv[i]);
  724. } else if (arg == "--ff") {
  725. if (++i >= argc) {
  726. invalid_param = true;
  727. break;
  728. }
  729. params->n_ff = std::stoi(argv[i]);
  730. } else if (arg == "--head") {
  731. if (++i >= argc) {
  732. invalid_param = true;
  733. break;
  734. }
  735. params->n_head = std::stoi(argv[i]);
  736. } else if (arg == "--layer") {
  737. if (++i >= argc) {
  738. invalid_param = true;
  739. break;
  740. }
  741. params->n_layer = std::stoi(argv[i]);
  742. } else if (arg == "--norm-rms-eps") {
  743. if (++i >= argc) {
  744. invalid_param = true;
  745. break;
  746. }
  747. params->f_norm_rms_eps = std::stof(argv[i]);
  748. } else if (arg == "--rope-freq-base") {
  749. if (++i >= argc) {
  750. invalid_param = true;
  751. break;
  752. }
  753. params->rope_freq_base = std::stof(argv[i]);
  754. } else if (arg == "--rope-freq-scale") {
  755. if (++i >= argc) {
  756. invalid_param = true;
  757. break;
  758. }
  759. params->rope_freq_scale = std::stof(argv[i]);
  760. } else {
  761. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  762. train_print_usage(argc, argv, &default_params);
  763. exit(1);
  764. }
  765. }
  766. if (invalid_param) {
  767. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  768. train_print_usage(argc, argv, &default_params);
  769. exit(1);
  770. }
  771. finish_processing_train_args(&params->common);
  772. return true;
  773. }
  774. struct save_train_files_data {
  775. const char * fn_checkpoint_out;
  776. const char * fn_model_out;
  777. const char * fn_vocab_model;
  778. const char * pattern_fn_it;
  779. const char * fn_latest;
  780. struct my_llama_model * model;
  781. };
  782. static void save_train_files(void * vdata, struct train_state * train) {
  783. struct save_train_files_data * data = (struct save_train_files_data *) vdata;
  784. int64_t iter = train->opt->iter;
  785. if (strlen(data->fn_checkpoint_out) > 0) {
  786. save_checkpoint_file(get_train_filename(data->fn_checkpoint_out, data->pattern_fn_it, data->fn_latest, iter).c_str(), data->fn_vocab_model, data->model, train);
  787. save_checkpoint_file(get_train_filename(data->fn_checkpoint_out, data->pattern_fn_it, data->fn_latest, -1 ).c_str(), data->fn_vocab_model, data->model, train);
  788. }
  789. if (strlen(data->fn_model_out) > 0) {
  790. save_llama_model_file(get_train_filename(data->fn_model_out, data->pattern_fn_it, data->fn_latest, iter).c_str(), data->fn_vocab_model, data->model);
  791. save_llama_model_file(get_train_filename(data->fn_model_out, data->pattern_fn_it, data->fn_latest, -1 ).c_str(), data->fn_vocab_model, data->model);
  792. }
  793. }
  794. static int64_t get_parameter_count(struct my_llama_model* model) {
  795. int64_t nx = 0;
  796. nx += ggml_nelements(model->tok_embeddings);
  797. nx += ggml_nelements(model->norm);
  798. nx += ggml_nelements(model->output);
  799. for (uint32_t i = 0; i < model->layers.size(); ++i) {
  800. auto & layer = model->layers[i];
  801. nx += ggml_nelements(layer.attention_norm);
  802. nx += ggml_nelements(layer.wq);
  803. nx += ggml_nelements(layer.wk);
  804. nx += ggml_nelements(layer.wv);
  805. nx += ggml_nelements(layer.wo);
  806. nx += ggml_nelements(layer.ffn_norm);
  807. nx += ggml_nelements(layer.w1);
  808. nx += ggml_nelements(layer.w2);
  809. nx += ggml_nelements(layer.w3);
  810. }
  811. return nx;
  812. }
  813. int main(int argc, char ** argv) {
  814. struct train_params params = get_default_train_params();
  815. if (!train_params_parse(argc, argv, &params)) {
  816. return 1;
  817. }
  818. if (params.common.seed == LLAMA_DEFAULT_SEED) {
  819. params.common.seed = time(NULL);
  820. }
  821. printf("%s: seed: %u\n", __func__, params.common.seed);
  822. srand(params.common.seed);
  823. struct llama_model_params mparams = llama_model_default_params();
  824. mparams.vocab_only = true;
  825. struct llama_context_params cparams = llama_context_default_params();
  826. struct llama_model * lmodel = llama_load_model_from_file(params.fn_vocab_model, mparams);
  827. struct llama_context * lctx = llama_new_context_with_model(lmodel, cparams);
  828. struct my_llama_model model;
  829. model.hparams.n_vocab = llama_n_vocab(lmodel);
  830. model.hparams.n_ctx = params.common.n_ctx;
  831. model.hparams.n_embd = params.n_embd;
  832. model.hparams.n_head = params.n_head;
  833. model.hparams.n_layer = params.n_layer;
  834. model.hparams.n_ff = params.n_ff;
  835. // llama.cpp requires n_rot to be exactly n_embd / n_head
  836. model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  837. model.hparams.f_norm_rms_eps = params.f_norm_rms_eps;
  838. model.hparams.rope_freq_base = params.rope_freq_base;
  839. model.hparams.rope_freq_scale = params.rope_freq_scale;
  840. struct train_state * train = init_train_state();
  841. struct ggml_opt_context * opt = train->opt;
  842. // set opt params from command line
  843. opt->params = ggml_opt_default_params(GGML_OPT_ADAM);
  844. opt->params.print_forward_graph = false;
  845. opt->params.print_backward_graph = false;
  846. opt->params.graph_size = LLAMA_TRAIN_MAX_NODES;
  847. opt->params.n_threads = params.common.n_threads;
  848. opt->params.past = params.common.opt_past;
  849. opt->params.delta = params.common.opt_delta;
  850. opt->params.max_no_improvement = params.common.opt_max_no_improvement;
  851. opt->params.n_gradient_accumulation = params.common.n_gradient_accumulation;
  852. opt->params.adam.n_iter = params.common.adam_n_iter;
  853. opt->params.adam.sched = 1.0f;
  854. opt->params.adam.alpha = params.common.adam_alpha;
  855. opt->params.adam.decay = params.common.adam_decay;
  856. opt->params.adam.decay_min_ndim = params.common.adam_decay_min_ndim;
  857. opt->params.adam.beta1 = params.common.adam_beta1;
  858. opt->params.adam.beta2 = params.common.adam_beta2;
  859. opt->params.adam.gclip = params.common.adam_gclip;
  860. opt->params.adam.eps_f = params.common.adam_eps_f;
  861. printf("%s: init model\n", __func__);
  862. bool existed = load_checkpoint_file(params.common.fn_checkpoint_in, &model, train);
  863. if (existed) {
  864. // overwrite last n_ctx with user provided n_ctx
  865. if (params.common.custom_n_ctx) {
  866. model.hparams.n_ctx = params.common.n_ctx;
  867. }
  868. const bool opt_past_changed = opt->params.past != params.common.opt_past;
  869. if (opt_past_changed) {
  870. die("Optimizer parameter '--opt-past N' differs from checkpoint file. To use different value train from scratch with empty input checkpoint, e.g --checkpoint-in ''. Aborting");
  871. // need to discard previous optimizer past function value statistics and opt_init with new shapes
  872. // TODO
  873. }
  874. } else {
  875. init_model(&model);
  876. randomize_model(&model, params.common.seed, 0.0f, 1.0f, -1.0f, +1.0f);
  877. if (!params.only_write_model) {
  878. ggml_opt_init(opt->ctx, opt, opt->params, get_parameter_count(&model));
  879. }
  880. }
  881. opt->iter = train->train_its;
  882. print_params(&model.hparams);
  883. printf("%s: total train_iterations %llu\n", __func__, (long long unsigned) train->train_its);
  884. printf("%s: seen train_samples %llu\n", __func__, (long long unsigned) train->train_samples);
  885. printf("%s: seen train_tokens %llu\n", __func__, (long long unsigned) train->train_tokens);
  886. printf("%s: completed train_epochs %llu\n", __func__, (long long unsigned) train->train_epochs);
  887. printf("%s: model_size = %zu bytes (%.1f MB)\n", __func__, (ggml_used_mem(model.ctx) + model.data.size()), (float) (ggml_used_mem(model.ctx) + model.data.size()) / (1024.0f*1024.0f));
  888. if (params.only_write_model) {
  889. save_train_files_data save_data;
  890. save_data.fn_checkpoint_out = "";
  891. save_data.fn_model_out = params.fn_model_out;
  892. save_data.fn_vocab_model = params.fn_vocab_model;
  893. save_data.pattern_fn_it = params.common.pattern_fn_it;
  894. save_data.fn_latest = params.common.fn_latest;
  895. save_data.model = &model;
  896. save_train_files(&save_data, train);
  897. free_train_state(train);
  898. ggml_free(model.ctx);
  899. llama_free(lctx);
  900. llama_free_model(lmodel);
  901. return 0;
  902. }
  903. printf("%s: opt_size = %zu bytes (%.1f MB)\n", __func__, ggml_get_mem_size(opt->ctx), (float) ggml_get_mem_size(opt->ctx) / (1024.0f*1024.0f));
  904. printf("%s: opt iter %d\n", __func__, opt->iter);
  905. int n_tokens = model.hparams.n_ctx;
  906. int n_vocab = model.hparams.n_vocab;
  907. int n_batch = params.common.n_batch;
  908. std::vector<uint8_t> mem_input_data;
  909. std::vector<uint8_t> mem_compute_data;
  910. ggml_allocr * alloc = NULL;
  911. // context for input tensors without their data
  912. struct ggml_init_params ctx_input_params = {
  913. ggml_tensor_overhead() * 2, // mem_size
  914. NULL, // mem_buffer
  915. true, // no_alloc
  916. };
  917. struct ggml_context * ctx_input = ggml_init(ctx_input_params);
  918. // the input tensors
  919. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx_input, GGML_TYPE_I32, n_tokens, n_batch);
  920. struct ggml_tensor * target_probs = ggml_new_tensor_3d(ctx_input, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  921. // measure required memory for input tensors
  922. size_t max_input_size = GGML_PAD(ggml_nbytes(tokens_input), tensor_alignment) +
  923. GGML_PAD(ggml_nbytes(target_probs), tensor_alignment) +
  924. tensor_alignment;
  925. printf("%s: input_size = %zu bytes (%.1f MB)\n", __func__, max_input_size, (float) max_input_size / (1024.0f*1024.0f));
  926. // allocate input tensors
  927. mem_input_data.resize(max_input_size);
  928. alloc = ggml_allocr_new(mem_input_data.data(), mem_input_data.size(), tensor_alignment);
  929. ggml_allocr_alloc(alloc, tokens_input);
  930. ggml_allocr_alloc(alloc, target_probs);
  931. ggml_allocr_free(alloc);
  932. // context for compute tensors without their data
  933. const size_t estimated_compute_size_wo_data = (
  934. 2*LLAMA_TRAIN_MAX_NODES*ggml_tensor_overhead() +
  935. (params.common.use_checkpointing ? 3 : 2)*(GGML_OBJECT_SIZE+ggml_graph_overhead_custom(LLAMA_TRAIN_MAX_NODES, true))
  936. );
  937. struct ggml_init_params ctx_compute_params = {
  938. estimated_compute_size_wo_data, // mem_size
  939. NULL, // mem_buffer
  940. true, // no_alloc
  941. };
  942. struct ggml_context * ctx_compute = NULL;
  943. struct ggml_tensor * loss = NULL;
  944. struct ggml_tensor * logits = NULL;
  945. struct ggml_cgraph * gf = NULL;
  946. struct ggml_cgraph * gb = NULL;
  947. struct ggml_cgraph * gb_tmp = NULL;
  948. // measure required memory for compute tensors
  949. size_t best_compute_size = SIZE_MAX;
  950. enum ggml_cgraph_eval_order best_order = GGML_CGRAPH_EVAL_ORDER_COUNT;
  951. // find best evaluation order
  952. for (unsigned order = 0; order < (unsigned) GGML_CGRAPH_EVAL_ORDER_COUNT; ++order) {
  953. ctx_compute = ggml_init(ctx_compute_params);
  954. alloc = ggml_allocr_new_measure(tensor_alignment);
  955. gf = ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true);
  956. gf->order = (enum ggml_cgraph_eval_order) order;
  957. gb = ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true);
  958. gb_tmp = params.common.use_checkpointing
  959. ? ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true)
  960. : NULL;
  961. loss = llama_build_train_graphs(
  962. &model, alloc, ctx_compute,
  963. gf, gb, gb_tmp,
  964. &logits, tokens_input, target_probs,
  965. n_tokens, n_batch,
  966. params.common.use_flash,
  967. params.common.use_checkpointing
  968. );
  969. size_t max_compute_size = ggml_allocr_max_size(alloc) + tensor_alignment;
  970. if (max_compute_size < best_compute_size) {
  971. best_compute_size = max_compute_size;
  972. best_order = gf->order;
  973. }
  974. ggml_allocr_free(alloc);
  975. ggml_free(ctx_compute);
  976. }
  977. size_t max_compute_size = best_compute_size;
  978. printf("%s: compute_size = %zu bytes (%.1f MB)\n", __func__, max_compute_size, (float) max_compute_size / (1024.0f*1024.0f));
  979. printf("%s: evaluation order = %s\n", __func__,
  980. (best_order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? "LEFT_TO_RIGHT" :
  981. (best_order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? "RIGHT_TO_LEFT" :
  982. "invalid");
  983. // allocate compute tensors
  984. mem_compute_data.resize(max_compute_size);
  985. ctx_compute = ggml_init(ctx_compute_params);
  986. alloc = ggml_allocr_new(mem_compute_data.data(), mem_compute_data.size(), tensor_alignment);
  987. gf = ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true);
  988. gf->order = best_order;
  989. gb = ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true);
  990. gb_tmp = params.common.use_checkpointing
  991. ? ggml_new_graph_custom(ctx_compute, LLAMA_TRAIN_MAX_NODES, true)
  992. : NULL;
  993. loss = llama_build_train_graphs(
  994. &model, alloc, ctx_compute,
  995. gf, gb, gb_tmp,
  996. &logits, tokens_input, target_probs,
  997. n_tokens, n_batch,
  998. params.common.use_flash,
  999. params.common.use_checkpointing
  1000. );
  1001. ggml_allocr_free(alloc);
  1002. std::vector<llama_token> train_tokens;
  1003. std::vector<size_t> train_samples_begin;
  1004. std::vector<size_t> train_samples_size;
  1005. printf("%s: tokenize training data\n", __func__);
  1006. tokenize_file(lctx,
  1007. params.common.fn_train_data,
  1008. params.common.sample_start,
  1009. params.common.include_sample_start,
  1010. params.common.overlapping_samples,
  1011. n_tokens,
  1012. train_tokens,
  1013. train_samples_begin,
  1014. train_samples_size);
  1015. GGML_ASSERT(train_samples_begin.size() == train_samples_size.size());
  1016. printf("%s: number of training tokens: %zu\n", __func__, train_tokens.size());
  1017. size_t shuffle_samples_hash = compute_samples_hash(params.common.fn_train_data, train_samples_begin.data(), train_samples_size.data(), train_samples_size.size());
  1018. const bool changed_train_data = (shuffle_samples_hash != train->shuffle_samples_hash) || (train->shuffle_sample_count != train_samples_size.size());
  1019. if (changed_train_data) {
  1020. printf("%s: train data seems to have changed. restarting shuffled epoch.\n", __func__);
  1021. }
  1022. if (params.common.force_reshuffle) {
  1023. printf("%s: forced reshuffling of data. restarting with newly shuffled epoch.\n", __func__);
  1024. }
  1025. if ((train->shuffle_rng_state_current == "") || changed_train_data || params.common.force_reshuffle) {
  1026. train->shuffle_rng_state_current = mt19937_seed_to_state(params.common.seed);
  1027. train->shuffle_sample_count = train_samples_size.size();
  1028. train->shuffle_next_sample = 0;
  1029. train->shuffle_samples_hash = shuffle_samples_hash;
  1030. }
  1031. std::vector<size_t> train_shuffled_samples_offs;
  1032. std::vector<size_t> train_shuffled_samples_begin;
  1033. std::vector<size_t> train_shuffled_samples_size;
  1034. train_shuffled_samples_offs.resize(train_samples_begin.size());
  1035. train_shuffled_samples_begin.resize(train_samples_begin.size());
  1036. train_shuffled_samples_size.resize(train_samples_size.size());
  1037. train->shuffle_rng_state_next = shuffle_samples(
  1038. train->shuffle_rng_state_current,
  1039. train_shuffled_samples_offs.data(),
  1040. train_shuffled_samples_begin.data(),
  1041. train_shuffled_samples_size.data(),
  1042. train_samples_begin.data(),
  1043. train_samples_size.data(),
  1044. train_samples_size.size());
  1045. printf("%s: begin training\n", __func__);
  1046. save_train_files_data save_data;
  1047. save_data.fn_checkpoint_out = params.common.fn_checkpoint_out;
  1048. save_data.fn_model_out = params.fn_model_out;
  1049. save_data.fn_vocab_model = params.fn_vocab_model;
  1050. save_data.pattern_fn_it = params.common.pattern_fn_it;
  1051. save_data.fn_latest = params.common.fn_latest;
  1052. save_data.model = &model;
  1053. struct train_opt_callback_data opt_cb_data;
  1054. opt_cb_data.params = &params.common;
  1055. opt_cb_data.train = train;
  1056. opt_cb_data.save_cb = &save_train_files;
  1057. opt_cb_data.save_data = &save_data;
  1058. opt_cb_data.lctx = lctx;
  1059. opt_cb_data.last_save_iter = opt->iter;
  1060. opt_cb_data.tokens_data = train_tokens.data();
  1061. opt_cb_data.tokens_size = train_tokens.size();
  1062. opt_cb_data.samples_begin = train_samples_begin.data();
  1063. opt_cb_data.samples_size = train_samples_size.data();
  1064. opt_cb_data.shuffled_samples_offs = train_shuffled_samples_offs.data();
  1065. opt_cb_data.shuffled_samples_begin = train_shuffled_samples_begin.data();
  1066. opt_cb_data.shuffled_samples_size = train_shuffled_samples_size.data();
  1067. opt_cb_data.samples_count = train_samples_size.size();
  1068. opt_cb_data.tokens_input = tokens_input;
  1069. opt_cb_data.target_probs = target_probs;
  1070. opt_cb_data.first_iter = opt->iter;
  1071. opt_cb_data.first_epoch = train->train_epochs;
  1072. opt_cb_data.iter_at_last_epoch = -1;
  1073. opt_cb_data.last_time = ggml_time_ms();
  1074. opt_cb_data.millis_per_iter = 0.0;
  1075. // measure required memory for work buffer
  1076. size_t max_work_size = ggml_graph_plan(gb, params.common.n_threads).work_size + GGML_OBJECT_SIZE;
  1077. printf("%s: work_size = %zu bytes (%.1f MB)\n", __func__, max_work_size, (float) max_work_size / (1024.0f*1024.0f));
  1078. // context for work buffer
  1079. struct ggml_init_params ctx_work_params = {
  1080. max_work_size, // mem_size
  1081. NULL, // mem_buffer
  1082. false, // no_alloc
  1083. };
  1084. struct ggml_context * ctx_work = ggml_init(ctx_work_params);
  1085. int64_t t0 = ggml_time_ms();
  1086. ggml_opt_resume_g(ctx_work, opt, loss, gf, gb, &train_opt_callback, (void *) &opt_cb_data);
  1087. ggml_free(ctx_work);
  1088. ggml_free(ctx_compute);
  1089. ggml_free(ctx_input);
  1090. int64_t t1 = ggml_time_ms();
  1091. printf("%s: total training time: ", __func__);
  1092. print_duration((double) (t1 - t0));
  1093. printf("\n");
  1094. int new_iters = opt->iter - opt_cb_data.last_save_iter;
  1095. if (new_iters > 0) {
  1096. train->train_its += new_iters;
  1097. train->train_tokens += new_iters * opt->params.n_gradient_accumulation * n_batch * n_tokens;
  1098. save_train_files(&save_data, train);
  1099. opt_cb_data.last_save_iter = opt->iter;
  1100. }
  1101. ggml_free(opt->ctx);
  1102. free_train_state(train);
  1103. ggml_free(model.ctx);
  1104. llama_free(lctx);
  1105. llama_free_model(lmodel);
  1106. return 0;
  1107. }