train-text-from-scratch.cpp 57 KB

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