convert-llama2c-to-ggml.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. #include "ggml.h"
  2. #include "llama.h"
  3. #include "common.h"
  4. #include "log.h"
  5. #include <unordered_map>
  6. #include <vector>
  7. #include <cassert>
  8. #include <climits>
  9. #include <cstring>
  10. #include <cstdarg>
  11. #include <ctime>
  12. #include <random>
  13. #include <stdexcept>
  14. #include <sstream>
  15. #include <algorithm>
  16. #include <string>
  17. // GGUF keys & tensor names.
  18. #define KV_GENERAL_ARCHITECTURE "general.architecture"
  19. #define KV_GENERAL_NAME "general.name"
  20. #define KV_TOKENIZER_MODEL "tokenizer.ggml.model"
  21. #define KV_TOKENIZER_LIST "tokenizer.ggml.tokens"
  22. #define KV_TOKENIZER_TOKEN_TYPE "tokenizer.ggml.token_type"
  23. #define KV_TOKENIZER_SCORES "tokenizer.ggml.scores"
  24. #define KV_TOKENIZER_BOS_ID "tokenizer.ggml.bos_token_id"
  25. #define KV_TOKENIZER_EOS_ID "tokenizer.ggml.eos_token_id"
  26. #define KV_TOKENIZER_UNK_ID "tokenizer.ggml.unknown_token_id"
  27. #define KV_TOKENIZER_SEP_ID "tokenizer.ggml.seperator_token_id"
  28. #define KV_TOKENIZER_PAD_ID "tokenizer.ggml.padding_token_id"
  29. #define KV_TOKENIZER_HF_JSON "tokenizer.huggingface.json"
  30. #define KV_CONTEXT_LENGTH "llama.context_length"
  31. #define KV_EMBEDDING_LENGTH "llama.embedding_length"
  32. #define KV_BLOCK_COUNT "llama.block_count"
  33. #define KV_FEED_FORWARD_LENGTH "llama.feed_forward_length"
  34. #define KV_ATTENTION_HEAD_COUNT "llama.attention.head_count"
  35. #define KV_ATTENTION_HEAD_COUNT_KV "llama.attention.head_count_kv"
  36. #define KV_ATTENTION_LAYERNORM_RMS_EPS "llama.attention.layer_norm_rms_epsilon"
  37. #define KV_ROPE_DIMENSION_COUNT "llama.rope.dimension_count"
  38. #define TN_TOKEN_EMBD "token_embd.weight"
  39. #define TN_OUTPUT_NORM "output_norm.weight"
  40. #define TN_OUTPUT "output.weight"
  41. #define TN_ATTN_NORM "blk.%d.attn_norm.weight"
  42. #define TN_ATTN_Q "blk.%d.attn_q.weight"
  43. #define TN_ATTN_K "blk.%d.attn_k.weight"
  44. #define TN_ATTN_V "blk.%d.attn_v.weight"
  45. #define TN_ATTN_OUTPUT "blk.%d.attn_output.weight"
  46. #define TN_FFN_NORM "blk.%d.ffn_norm.weight"
  47. #define TN_FFN_GATE "blk.%d.ffn_gate.weight"
  48. #define TN_FFN_DOWN "blk.%d.ffn_down.weight"
  49. #define TN_FFN_UP "blk.%d.ffn_up.weight"
  50. #if defined(_MSC_VER)
  51. #pragma warning(disable: 4244 4267) // possible loss of data
  52. #endif
  53. #define LLAMA_FILE_MAGIC_GGJT 0x67676a74u // 'ggjt'
  54. #define LLAMA_FILE_VERSION_GGJT_V3 3
  55. #define TOKENIZER_NAME "llama"
  56. #define UNKNOWN_TOKEN_ID 0
  57. #define BOS_TOKEN_ID 1
  58. #define EOS_TOKEN_ID 2
  59. //////////////////////////////////////// llama2.c model structs and functions to load models, alloc memory etc.
  60. typedef struct {
  61. int dim; // transformer dimension
  62. int hidden_dim; // for ffn layers
  63. int n_layers; // number of layers
  64. int n_heads; // number of query heads
  65. int n_kv_heads; // number of key/value heads (can be < query heads because of multiquery)
  66. int vocab_size; // vocabulary size, usually 256 (byte-level)
  67. int seq_len; // max sequence length
  68. } Config;
  69. struct TransformerWeights {
  70. // token embedding table
  71. std::vector<float> token_embedding_table; // (vocab_size, dim)
  72. // weights for rmsnorms
  73. std::vector<float> rms_att_weight; // (layer, dim) rmsnorm weights
  74. std::vector<float> rms_ffn_weight; // (layer, dim)
  75. // weights for matmuls
  76. std::vector<float> wq; // (layer, dim, dim)
  77. std::vector<float> wk; // (layer, dim, dim)
  78. std::vector<float> wv; // (layer, dim, dim)
  79. std::vector<float> wo; // (layer, dim, dim)
  80. // weights for ffn
  81. std::vector<float> w1; // (layer, hidden_dim, dim)
  82. std::vector<float> w2; // (layer, dim, hidden_dim)
  83. std::vector<float> w3; // (layer, hidden_dim, dim)
  84. // final rmsnorm
  85. std::vector<float> rms_final_weight; // (dim,)
  86. // freq_cis for RoPE relatively positional embeddings
  87. // std::vector<float> freq_cis_real; // (seq_len, dim/2)
  88. // std::vector<float> freq_cis_imag; // (seq_len, dim/2)
  89. // (optional) classifier weights for the logits, on the last layer
  90. std::vector<float> wcls;
  91. };
  92. static void alloc_weights(TransformerWeights * w, const Config * p, bool shared_weights) {
  93. const int n_multiqueries = p->n_kv_heads <= 0 || p->n_kv_heads >= p->n_heads ? 1 : p->n_heads / p->n_kv_heads;
  94. try {
  95. w->token_embedding_table.resize(p->vocab_size * p->dim);
  96. LOG("%s: Allocating [%d] x [%d] = [%d] float space for w->token_embedding_table\n",__func__,p->vocab_size , p->dim, p->vocab_size * p->dim);
  97. w->rms_att_weight.resize(p->n_layers * p->dim);
  98. LOG("%s: Allocating [%d] x [%d] = [%d] float space for w->rms_att_weight\n",__func__,p->n_layers, p->dim, p->n_layers * p->dim);
  99. w->rms_ffn_weight.resize(p->n_layers * p->dim);
  100. LOG("%s: Allocating [%d] x [%d] = [%d] float space for w->rms_ffn_weight\n",__func__,p->n_layers , p->dim, p->n_layers * p->dim);
  101. w->wq.resize(p->n_layers * p->dim * p->dim);
  102. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->wq\n",__func__,p->n_layers, p->dim, p->dim, p->n_layers * p->dim * p->dim);
  103. w->wk.resize(p->n_layers * p->dim * p->dim / n_multiqueries);
  104. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->wk\n",__func__,p->n_layers, p->dim, p->dim / n_multiqueries, p->n_layers * p->dim * p->dim / n_multiqueries);
  105. w->wv.resize(p->n_layers * p->dim * p->dim / n_multiqueries);
  106. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->wv\n",__func__, p->n_layers, p->dim, p->dim / n_multiqueries, p->n_layers * p->dim * p->dim / n_multiqueries);
  107. w->wo.resize(p->n_layers * p->dim * p->dim);
  108. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->wo\n",__func__,p->n_layers, p->dim, p->dim, p->n_layers * p->dim * p->dim);
  109. w->w1.resize(p->n_layers * p->hidden_dim * p->dim);
  110. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w1\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim);
  111. w->w2.resize(p->n_layers * p->hidden_dim * p->dim);
  112. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w2\n",__func__,p->n_layers, p->dim, p->hidden_dim, p->n_layers * p->hidden_dim * p->dim);
  113. w->w3.resize(p->n_layers * p->hidden_dim * p->dim);
  114. LOG("%s: Allocating [%d] x [%d] x [%d] = [%d] float space for w->w3\n",__func__,p->n_layers, p->hidden_dim, p->dim, p->n_layers * p->hidden_dim * p->dim);
  115. w->rms_final_weight.resize(p->dim);
  116. LOG("%s: Allocating [%d] float space for w->rms_final_weight\n",__func__,p->dim);
  117. if (shared_weights) {
  118. w->wcls = {};
  119. } else {
  120. w->wcls.resize(p->vocab_size * p->dim);
  121. LOG("%s: Allocating [%d] x [%d] = [%d] float space for w->wcls\n",__func__,p->vocab_size , p->dim, p->vocab_size * p->dim);
  122. }
  123. }
  124. catch (std::length_error &) {
  125. die("Invalid configuration. Failed to allocate memory for weights");
  126. }
  127. }
  128. static int checkpoint_init_weights(TransformerWeights * w, const Config * p, FILE * f, bool shared_weights) {
  129. if (fread(w->token_embedding_table.data(), sizeof(float), w->token_embedding_table.size(), f) != w->token_embedding_table.size()) return 1;
  130. if (fread(w->rms_att_weight.data(), sizeof(float), w->rms_att_weight.size(), f) != w->rms_att_weight.size()) return 1;
  131. if (fread(w->wq.data(), sizeof(float), w->wq.size(), f) != w->wq.size()) return 1;
  132. if (fread(w->wk.data(), sizeof(float), w->wk.size(), f) != w->wk.size()) return 1;
  133. if (fread(w->wv.data(), sizeof(float), w->wv.size(), f) != w->wv.size()) return 1;
  134. if (fread(w->wo.data(), sizeof(float), w->wo.size(), f) != w->wo.size()) return 1;
  135. if (fread(w->rms_ffn_weight.data(), sizeof(float), w->rms_ffn_weight.size(), f) != w->rms_ffn_weight.size()) return 1;
  136. if (fread(w->w1.data(), sizeof(float), w->w1.size(), f) != w->w1.size()) return 1;
  137. if (fread(w->w2.data(), sizeof(float), w->w2.size(), f) != w->w2.size()) return 1;
  138. if (fread(w->w3.data(), sizeof(float), w->w3.size(), f) != w->w3.size()) return 1;
  139. if (fread(w->rms_final_weight.data(), sizeof(float), w->rms_final_weight.size(), f) != w->rms_final_weight.size()) return 1;
  140. // Skip freq_cis_real & freq_cis_imag
  141. int head_size = p->dim / p->n_heads;
  142. fseek(f, p->seq_len * head_size * sizeof(float), SEEK_CUR);
  143. if (!shared_weights && fread(w->wcls.data(), sizeof(float), w->wcls.size(), f) != w->wcls.size()) return 1;
  144. // Check we didn't forget to read anything
  145. auto curr = ftell(f);
  146. fseek(f, 0, SEEK_END);
  147. auto end = ftell(f);
  148. if (curr != end) {
  149. LOG("%s: Error: failed to read the checkpoint file to the end (curr = %ld, end = %ld)\n", __func__, curr, end);
  150. return 1;
  151. }
  152. return 0;
  153. }
  154. static void print_sample_weights(TransformerWeights *w){
  155. LOG("----- Quick print of first of the weight vales of all the variables\n");
  156. LOG("%f\n", w->token_embedding_table[0]);
  157. LOG("%f\n", w->rms_att_weight[0]);
  158. LOG("%f\n", w->rms_ffn_weight[0]);
  159. LOG("%f\n", w->wq[0]);
  160. LOG("%f\n", w->wk[0]);
  161. LOG("%f\n", w->wv[0]);
  162. LOG("%f\n", w->wo[0]);
  163. LOG("%f\n", w->w1[0]);
  164. LOG("%f\n", w->w2[0]);
  165. LOG("%f\n", w->w3[0]);
  166. LOG("%f\n", w->rms_att_weight[0]);
  167. if (!w->wcls.empty()) LOG("%f\n", w->wcls[0]);
  168. }
  169. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  170. //////////////////////////////////////// ggml structs and functions required to load models, configs and save the model.
  171. struct llama_vocab {
  172. using id = int32_t;
  173. using token = std::string;
  174. using ttype = llama_token_type;
  175. struct token_data {
  176. token text;
  177. float score;
  178. ttype type;
  179. };
  180. std::unordered_map<token, id> token_to_id;
  181. std::vector<token_data> id_to_token;
  182. };
  183. struct my_llama_hparams {
  184. uint32_t n_vocab = 32000;
  185. uint32_t n_ctx = 512; // this is provided as user input?
  186. uint32_t n_embd = 4096;
  187. uint32_t n_ff = 11008;
  188. uint32_t n_mult = 4;
  189. uint32_t n_head = 32;
  190. uint32_t n_head_kv = 32;
  191. uint32_t n_layer = 32;
  192. uint32_t n_rot = 64;
  193. bool operator!=(const my_llama_hparams& other) const {
  194. return memcmp(this, &other, sizeof(my_llama_hparams));
  195. }
  196. };
  197. struct my_llama_layer {
  198. // normalization
  199. struct ggml_tensor * attention_norm;
  200. // attention
  201. struct ggml_tensor * wq;
  202. struct ggml_tensor * wk;
  203. struct ggml_tensor * wv;
  204. struct ggml_tensor * wo;
  205. // normalization
  206. struct ggml_tensor * ffn_norm;
  207. // ff
  208. struct ggml_tensor * w1;
  209. struct ggml_tensor * w2;
  210. struct ggml_tensor * w3;
  211. };
  212. struct my_llama_model {
  213. struct ggml_context * ctx = NULL;
  214. std::string name;
  215. my_llama_hparams hparams;
  216. struct ggml_tensor * tok_embeddings;
  217. struct ggml_tensor * norm;
  218. struct ggml_tensor * output;
  219. std::vector<my_llama_layer> layers;
  220. uint32_t train_its = 0;
  221. uint32_t train_samples = 0;
  222. uint32_t train_tokens = 0;
  223. };
  224. struct train_params {
  225. const char * fn_vocab_model;
  226. const char * fn_llama2c_model;
  227. const char * fn_llama2c_output_model;
  228. const char * fn_train_data;
  229. const char * fn_checkpoint_in;
  230. const char * fn_checkpoint_out;
  231. const char * fn_model_out;
  232. uint32_t seed;
  233. int n_ctx;
  234. int n_embd;
  235. int n_mult;
  236. int n_head;
  237. int n_layer;
  238. int n_rotmax;
  239. int n_threads;
  240. int n_batch;
  241. int n_examples;
  242. int n_predict;
  243. int print_info_interval;
  244. int print_details_interval;
  245. bool samples_start_after_nl;
  246. bool use_adam;
  247. bool use_flash;
  248. bool use_scratch;
  249. // only adam
  250. int warmup;
  251. int cos_decay_steps;
  252. float cos_decay_restart;
  253. float cos_decay_alpha;
  254. int lbfgs_n_iter;
  255. int adam_n_iter;
  256. float adam_alpha;
  257. float adam_decay;
  258. int mem_model_gb;
  259. int mem_compute_gb;
  260. int mem_compute0_gb;
  261. int mem_compute1_gb;
  262. };
  263. static void print_params(struct my_llama_hparams * params) {
  264. LOG("%s: n_vocab: %u\n", __func__, params->n_vocab);
  265. LOG("%s: n_ctx: %u\n", __func__, params->n_ctx);
  266. LOG("%s: n_embd: %u\n", __func__, params->n_embd);
  267. LOG("%s: n_mult: %u\n", __func__, params->n_mult);
  268. LOG("%s: n_head: %u\n", __func__, params->n_head);
  269. LOG("%s: n_head_kv: %u\n", __func__, params->n_head_kv);
  270. LOG("%s: n_ff: %u\n", __func__, params->n_ff);
  271. LOG("%s: n_layer: %u\n", __func__, params->n_layer);
  272. LOG("%s: n_rot: %u\n", __func__, params->n_rot);
  273. }
  274. static void print_tensor_info(const struct ggml_context * ctx) {
  275. for (auto t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  276. LOG("%s: Allocating ", __func__);
  277. int64_t total = 1;
  278. int i = 0;
  279. for (; i < ggml_n_dims(t); ++i) {
  280. if (i > 0) LOG("x ");
  281. LOG("[%" PRId64 "] ", t->ne[i]);
  282. total *= t->ne[i];
  283. }
  284. if (i > 1) LOG("= [%" PRId64 "] ", total);
  285. LOG("float space for %s\n", ggml_get_name(t));
  286. }
  287. }
  288. static void init_model(struct my_llama_model * model) {
  289. const auto & hparams = model->hparams;
  290. const uint32_t n_embd = hparams.n_embd;
  291. const uint32_t n_layer = hparams.n_layer;
  292. const uint32_t n_vocab = hparams.n_vocab;
  293. const uint32_t n_multiqueries = hparams.n_head_kv <= 0 || hparams.n_head_kv >= hparams.n_head ? 1 : hparams.n_head / hparams.n_head_kv;
  294. const uint32_t n_ff = hparams.n_ff;
  295. struct ggml_context * ctx = model->ctx;
  296. model->train_its = 0;
  297. model->train_samples = 0;
  298. model->train_tokens = 0;
  299. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  300. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  301. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab);
  302. ggml_set_name(model->tok_embeddings, "tok_embeddings.weight");
  303. ggml_set_name(model->norm, "norm.weight");
  304. ggml_set_name(model->output, "output.weight");
  305. model->layers.resize(n_layer);
  306. for (uint32_t i = 0; i < n_layer; ++i) {
  307. auto & layer = model->layers[i];
  308. std::string layers_i = "layers." + std::to_string(i);
  309. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  310. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  311. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd / n_multiqueries);
  312. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd / n_multiqueries);
  313. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd);
  314. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  315. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  316. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd);
  317. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff);
  318. ggml_set_name(layer.attention_norm, (layers_i + ".attention_norm.weight").c_str());
  319. ggml_set_name(layer.wq, (layers_i + ".attention.wq.weight").c_str());
  320. ggml_set_name(layer.wk, (layers_i + ".attention.wk.weight").c_str());
  321. ggml_set_name(layer.wv, (layers_i + ".attention.wv.weight").c_str());
  322. ggml_set_name(layer.wo, (layers_i + ".attention.wo.weight").c_str());
  323. ggml_set_name(layer.ffn_norm, (layers_i + ".ffn_norm.weight").c_str());
  324. ggml_format_name(layer.w1, "%s.feed_forward.w1.weight", layers_i.c_str());
  325. ggml_format_name(layer.w2, "%s.feed_forward.w2.weight", layers_i.c_str());
  326. ggml_format_name(layer.w3, "%s.feed_forward.w3.weight", layers_i.c_str());
  327. }
  328. print_tensor_info(ctx);
  329. }
  330. static float get_f32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  331. float * ptr = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  332. return *ptr;
  333. }
  334. static int32_t get_i32_2d(struct ggml_tensor * tensor, int64_t i0, int64_t i1) {
  335. int32_t * ptr = (int32_t *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  336. return *ptr;
  337. }
  338. static void print_row(struct ggml_tensor * probs, int i) {
  339. for (int k = 0; k < probs->ne[0]; ++k) {
  340. float p = get_f32_2d(probs, k, i);
  341. LOG(" %f", p);
  342. }
  343. LOG("\n");
  344. }
  345. static void print_matrix(struct ggml_tensor * probs) {
  346. assert(ggml_is_matrix(probs));
  347. for (int i = 0; i < probs->ne[1]; ++i) {
  348. for (int k = 0; k < probs->ne[0]; ++k) {
  349. float p = get_f32_2d(probs, k, i);
  350. LOG(" %.2f", p);
  351. }
  352. LOG("\n");
  353. }
  354. }
  355. struct llama_file {
  356. // use FILE * so we don't have to re-open the file to mmap
  357. FILE * fp;
  358. size_t size;
  359. llama_file(const char * fname, const char * mode) {
  360. fp = std::fopen(fname, mode);
  361. if (fp == NULL) {
  362. size = 0;
  363. } else {
  364. seek(0, SEEK_END);
  365. size = tell();
  366. seek(0, SEEK_SET);
  367. }
  368. }
  369. size_t tell() const {
  370. #ifdef _WIN32
  371. __int64 ret = _ftelli64(fp);
  372. #else
  373. long ret = std::ftell(fp);
  374. #endif
  375. GGML_ASSERT(ret != -1); // this really shouldn't fail
  376. return (size_t) ret;
  377. }
  378. void seek(size_t offset, int whence) {
  379. #ifdef _WIN32
  380. int ret = _fseeki64(fp, (__int64) offset, whence);
  381. #else
  382. int ret = std::fseek(fp, (long) offset, whence);
  383. #endif
  384. GGML_ASSERT(ret == 0); // same
  385. }
  386. void read_raw(void * ptr, size_t size) {
  387. if (size == 0) {
  388. return;
  389. }
  390. errno = 0;
  391. std::size_t ret = std::fread(ptr, size, 1, fp);
  392. if (ferror(fp)) {
  393. die_fmt("fread failed: %s", strerror(errno));
  394. }
  395. if (ret != 1) {
  396. die("unexpectedly reached end of file");
  397. }
  398. }
  399. std::uint32_t read_u32() {
  400. std::uint32_t ret;
  401. read_raw(&ret, sizeof(ret));
  402. return ret;
  403. }
  404. std::float_t read_f32() {
  405. std::float_t ret;
  406. read_raw(&ret, sizeof(ret));
  407. return ret;
  408. }
  409. std::string read_string(std::uint32_t len) {
  410. std::vector<char> chars(len);
  411. read_raw(chars.data(), len);
  412. return std::string(chars.data(), len);
  413. }
  414. ~llama_file() {
  415. if (fp) {
  416. std::fclose(fp);
  417. }
  418. }
  419. };
  420. static bool is_ggml_file(const char * filename) {
  421. llama_file file(filename, "rb");
  422. if (file.size < 4) {
  423. return false;
  424. }
  425. std::string magic = file.read_string(4);
  426. return magic == GGUF_MAGIC;
  427. }
  428. static std::string llama_escape_whitespaces(const std::string & text) {
  429. std::ostringstream out;
  430. for (char c : text) {
  431. if (c == ' ') out << "\xe2\x96\x81";
  432. else out << c;
  433. }
  434. return out.str();
  435. }
  436. static void load_vocab(const char * filename, const Config * config, struct llama_vocab * vocab) {
  437. if (is_ggml_file(filename)) {
  438. LOG("%s: Loading vocabulary from gguf file %s\n", __func__, filename);
  439. struct ggml_context * ctx_data = NULL;
  440. struct gguf_init_params params = {
  441. /*.no_alloc = */ false,
  442. /*.ctx = */ &ctx_data,
  443. };
  444. struct gguf_context * ctx = gguf_init_from_file(filename, params);
  445. GGML_ASSERT(ctx != NULL);
  446. const int model_idx = gguf_find_key(ctx, KV_TOKENIZER_MODEL);
  447. GGML_ASSERT(model_idx >= 0);
  448. std::string tokenizer_name = gguf_get_val_str(ctx, model_idx);
  449. GGML_ASSERT(tokenizer_name == TOKENIZER_NAME);
  450. const int token_idx = gguf_find_key(ctx, KV_TOKENIZER_LIST);
  451. GGML_ASSERT(token_idx >= 0);
  452. const int score_idx = gguf_find_key(ctx, KV_TOKENIZER_SCORES);
  453. GGML_ASSERT(score_idx >= 0);
  454. const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  455. const int toktype_idx = gguf_find_key(ctx, KV_TOKENIZER_TOKEN_TYPE);
  456. GGML_ASSERT(toktype_idx >= 0);
  457. const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  458. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  459. if (n_vocab != static_cast<uint32_t>(config->vocab_size)) {
  460. die_fmt("vocab size mismatch: (gguf) %u != (llama2c) %d", n_vocab, config->vocab_size);
  461. }
  462. vocab->id_to_token.resize(n_vocab);
  463. for (uint32_t i = 0; i < n_vocab; i++) {
  464. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  465. vocab->token_to_id[word] = i;
  466. auto & token_data = vocab->id_to_token[i];
  467. token_data.text = std::move(word);
  468. token_data.score = scores[i];
  469. token_data.type = (llama_token_type) toktypes[i];
  470. }
  471. ggml_free(ctx_data);
  472. gguf_free(ctx);
  473. } else {
  474. // assume llama2.c vocabulary
  475. LOG("%s: Assuming llama2.c vocabulary since %s is not a gguf file\n", __func__, filename);
  476. llama_file file(filename, "rb");
  477. if (!file.fp) {
  478. die_fmt("%s: %s", strerror(errno), filename);
  479. }
  480. const int n_vocab = config->vocab_size;
  481. /* uint32_t max_token_length = */ file.read_u32(); // unused
  482. vocab->id_to_token.resize(n_vocab);
  483. for (llama_vocab::id id=0; id<n_vocab; ++id) {
  484. float_t score = file.read_f32();
  485. uint32_t len = file.read_u32();
  486. std::string text = file.read_string(len);
  487. unsigned char byte_val;
  488. llama_vocab::ttype type = LLAMA_TOKEN_TYPE_NORMAL;
  489. if (id == UNKNOWN_TOKEN_ID) {
  490. text = "<unk>";
  491. type = LLAMA_TOKEN_TYPE_UNKNOWN;
  492. } else if (id == BOS_TOKEN_ID) {
  493. text = "<s>";
  494. type = LLAMA_TOKEN_TYPE_CONTROL;
  495. } else if (id == EOS_TOKEN_ID) {
  496. text = "</s>";
  497. type = LLAMA_TOKEN_TYPE_CONTROL;
  498. } else if (text.empty()) {
  499. type = LLAMA_TOKEN_TYPE_CONTROL;
  500. } else if (sscanf(text.c_str(), "<0x%02hhX>", &byte_val) == 1) {
  501. // Text of byte tokens is already in the expected format.
  502. type = LLAMA_TOKEN_TYPE_BYTE;
  503. } else {
  504. type = LLAMA_TOKEN_TYPE_NORMAL;
  505. }
  506. text = llama_escape_whitespaces(text);
  507. vocab->id_to_token[id].text = text;
  508. vocab->id_to_token[id].score = score;
  509. vocab->id_to_token[id].type = type;
  510. vocab->token_to_id.emplace(text, id);
  511. }
  512. }
  513. }
  514. static void convert_weights_ak_to_gg(struct ggml_tensor * gg_weights, const float * karpathy_weights) {
  515. int size = 1;
  516. for (int dim = 0; dim < ggml_n_dims(gg_weights); ++dim) {
  517. size *= gg_weights->ne[dim];
  518. }
  519. for (int ct = 0; ct < size; ++ct) {
  520. int64_t i0 = 0; int64_t i1 = 0;
  521. int64_t i2 = 0; int64_t i3 = 0;
  522. ggml_unravel_index(gg_weights, ct, &i0, &i1, &i2, &i3);
  523. ggml_set_f32_nd(gg_weights, i0, i1, i2, i3, karpathy_weights[ct]);
  524. }
  525. }
  526. static void save_as_llama_model(
  527. struct llama_vocab * vocab, struct my_llama_model * model, TransformerWeights* w, const char * filename
  528. ) {
  529. // convert AK weights into GG weights one by one.
  530. // w->token_embedding_table -> model->tok_embeddings
  531. // float* -> struct ggml_tensor
  532. convert_weights_ak_to_gg(model->tok_embeddings, w->token_embedding_table.data());
  533. convert_weights_ak_to_gg(model->output, !w->wcls.empty() ? w->wcls.data() : w->token_embedding_table.data());
  534. convert_weights_ak_to_gg(model->norm, w->rms_final_weight.data());
  535. //print_row(model->norm, 0);
  536. // for rms-att-weight
  537. int row_length = model->hparams.n_embd;
  538. int n_ff = model->hparams.n_ff;
  539. const uint32_t n_multiqueries = model->hparams.n_head_kv <= 0 || model->hparams.n_head_kv >= model->hparams.n_head ? 1 : model->hparams.n_head / model->hparams.n_head_kv;
  540. for (uint32_t i = 0; i < model->hparams.n_layer; ++i){
  541. auto & layer = model->layers[i];
  542. // 1d
  543. convert_weights_ak_to_gg(layer.attention_norm, &w->rms_att_weight[i*row_length]);
  544. convert_weights_ak_to_gg(layer.ffn_norm , &w->rms_ffn_weight[i*row_length]);
  545. // from 3d matrix layer x dim x dim to 2d matrix dim x dim
  546. convert_weights_ak_to_gg(layer.wq , &w->wq[i*row_length*row_length]);
  547. convert_weights_ak_to_gg(layer.wo , &w->wo[i*row_length*row_length]);
  548. // from 3d matrix layer x dim x dim to 2d matrix dim x dim / n_multiqueries
  549. convert_weights_ak_to_gg(layer.wk , &w->wk[i*row_length*row_length/n_multiqueries]);
  550. convert_weights_ak_to_gg(layer.wv , &w->wv[i*row_length*row_length/n_multiqueries]);
  551. convert_weights_ak_to_gg(layer.w1 , &w->w1[i*row_length*n_ff]);
  552. convert_weights_ak_to_gg(layer.w2 , &w->w2[i*n_ff*row_length]);
  553. convert_weights_ak_to_gg(layer.w3 , &w->w3[i*row_length*n_ff]);
  554. }
  555. struct gguf_context * ctx = gguf_init_empty();
  556. std::vector<const char*> tokens;
  557. std::vector<float> scores;
  558. std::vector<llama_token_type> token_types;
  559. for (const llama_vocab::token_data & token_data : vocab->id_to_token) {
  560. tokens.push_back(token_data.text.c_str());
  561. scores.push_back(token_data.score);
  562. token_types.push_back(token_data.type);
  563. }
  564. gguf_set_arr_str(ctx, KV_TOKENIZER_LIST, tokens.data(), tokens.size());
  565. gguf_set_arr_data(ctx, KV_TOKENIZER_SCORES, GGUF_TYPE_FLOAT32, scores.data(), scores.size());
  566. gguf_set_arr_data(ctx, KV_TOKENIZER_TOKEN_TYPE, GGUF_TYPE_INT32, token_types.data(), token_types.size());
  567. gguf_set_val_str(ctx, KV_TOKENIZER_MODEL, TOKENIZER_NAME);
  568. gguf_set_val_str(ctx, KV_GENERAL_ARCHITECTURE, "llama");
  569. gguf_set_val_str(ctx, KV_GENERAL_NAME, "llama");
  570. // special tokens
  571. gguf_set_val_u32(ctx, KV_TOKENIZER_UNK_ID, UNKNOWN_TOKEN_ID);
  572. gguf_set_val_u32(ctx, KV_TOKENIZER_BOS_ID, BOS_TOKEN_ID);
  573. gguf_set_val_u32(ctx, KV_TOKENIZER_EOS_ID, EOS_TOKEN_ID);
  574. gguf_set_val_u32(ctx, KV_TOKENIZER_SEP_ID, -1);
  575. gguf_set_val_u32(ctx, KV_TOKENIZER_PAD_ID, -1);
  576. gguf_set_val_u32(ctx, KV_CONTEXT_LENGTH, model->hparams.n_ctx);
  577. gguf_set_val_u32(ctx, KV_EMBEDDING_LENGTH, model->hparams.n_embd);
  578. gguf_set_val_u32(ctx, KV_FEED_FORWARD_LENGTH, model->hparams.n_ff);
  579. gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head);
  580. gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT, model->hparams.n_head);
  581. gguf_set_val_u32(ctx, KV_ATTENTION_HEAD_COUNT_KV, model->hparams.n_head_kv);
  582. gguf_set_val_u32(ctx, KV_BLOCK_COUNT, model->hparams.n_layer);
  583. gguf_set_val_u32(ctx, KV_ROPE_DIMENSION_COUNT, model->hparams.n_rot);
  584. gguf_set_val_f32(ctx, KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f);
  585. // write tensors
  586. ggml_set_name(model->tok_embeddings, TN_TOKEN_EMBD);
  587. gguf_add_tensor(ctx, model->tok_embeddings);
  588. ggml_set_name(model->norm, TN_OUTPUT_NORM);
  589. gguf_add_tensor(ctx, model->norm);
  590. ggml_set_name(model->output, TN_OUTPUT);
  591. gguf_add_tensor(ctx, model->output);
  592. for (uint32_t i = 0; i < model->hparams.n_layer; ++i) {
  593. auto & layer = model->layers[i];
  594. ggml_format_name(layer.wq, TN_ATTN_Q, i);
  595. gguf_add_tensor(ctx, layer.wq);
  596. ggml_format_name(layer.wk, TN_ATTN_K, i);
  597. gguf_add_tensor(ctx, layer.wk);
  598. ggml_format_name(layer.wv, TN_ATTN_V, i);
  599. gguf_add_tensor(ctx, layer.wv);
  600. ggml_format_name(layer.wo, TN_ATTN_OUTPUT, i);
  601. gguf_add_tensor(ctx, layer.wo);
  602. ggml_format_name(layer.attention_norm, TN_ATTN_NORM, i);
  603. gguf_add_tensor(ctx, layer.attention_norm);
  604. ggml_format_name(layer.w1, TN_FFN_GATE, i);
  605. gguf_add_tensor(ctx, layer.w1);
  606. ggml_format_name(layer.w2, TN_FFN_DOWN, i);
  607. gguf_add_tensor(ctx, layer.w2);
  608. ggml_format_name(layer.w3, TN_FFN_UP, i);
  609. gguf_add_tensor(ctx, layer.w3);
  610. ggml_format_name(layer.ffn_norm, TN_FFN_NORM, i);
  611. gguf_add_tensor(ctx, layer.ffn_norm);
  612. }
  613. gguf_write_to_file(ctx, filename, false);
  614. gguf_free(ctx);
  615. }
  616. static struct train_params get_default_train_params() {
  617. struct train_params params;
  618. params.fn_vocab_model = "models/7B/ggml-model-f16.gguf";
  619. params.fn_llama2c_output_model = "ak_llama_model.bin";
  620. params.fn_train_data = "shakespeare.txt";
  621. params.fn_checkpoint_in = "checkpoint.bin";
  622. params.fn_checkpoint_out = "checkpoint.bin";
  623. params.fn_model_out = "ggml-checkpoint-f32.bin";
  624. params.seed = -1;
  625. params.n_ctx = 128;
  626. params.n_embd = 256;
  627. params.n_mult = 256;
  628. params.n_head = 8;
  629. params.n_layer = 16;
  630. params.n_rotmax = 64;
  631. params.n_threads = 6;
  632. params.n_batch = 8;
  633. params.n_examples = 8;
  634. params.n_predict = 1024;
  635. params.print_info_interval = 1;
  636. params.print_details_interval = 2;
  637. params.samples_start_after_nl = false;
  638. params.use_adam = true;
  639. params.use_flash = true;
  640. params.use_scratch = true;
  641. // only adam
  642. params.warmup = 100;
  643. params.cos_decay_steps = 1000;
  644. params.cos_decay_restart = 1.1f;
  645. params.cos_decay_alpha = 0.0f;
  646. params.lbfgs_n_iter = 16;
  647. params.adam_n_iter = 16;
  648. params.adam_alpha = 1e-3f;
  649. params.adam_decay = 1e-3f;
  650. params.mem_model_gb = 2;
  651. params.mem_compute_gb = 24;
  652. params.mem_compute0_gb = 8;
  653. params.mem_compute1_gb = 2;
  654. return params;
  655. }
  656. static void print_usage(int /*argc*/, char ** argv, const struct train_params * params) {
  657. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  658. fprintf(stderr, "\n");
  659. fprintf(stderr, "options:\n");
  660. fprintf(stderr, " -h, --help show this help message and exit\n");
  661. fprintf(stderr, " --copy-vocab-from-model FNAME path of gguf llama model or llama2.c vocabulary from which to copy vocab (default '%s')\n", params->fn_vocab_model);
  662. fprintf(stderr, " --llama2c-model FNAME [REQUIRED] model path from which to load Karpathy's llama2.c model\n");
  663. fprintf(stderr, " --llama2c-output-model FNAME model path to save the converted llama2.c model (default %s')\n", params->fn_llama2c_output_model);
  664. fprintf(stderr, "\n");
  665. }
  666. static bool params_parse(int argc, char ** argv, struct train_params * params) {
  667. bool invalid_param = false;
  668. bool reqd_param_found = false;
  669. std::string arg;
  670. struct train_params default_params = get_default_train_params();
  671. const std::string arg_prefix = "--";
  672. for (int i = 1; i < argc; i++) {
  673. arg = argv[i];
  674. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  675. std::replace(arg.begin(), arg.end(), '_', '-');
  676. }
  677. if (arg == "--copy-vocab-from-model") {
  678. if (++i >= argc) {
  679. invalid_param = true;
  680. break;
  681. }
  682. params->fn_vocab_model = argv[i];
  683. } else if (arg == "--llama2c-model") {
  684. if (++i >= argc) {
  685. invalid_param = true;
  686. break;
  687. }
  688. reqd_param_found = true;
  689. params->fn_llama2c_model = argv[i];
  690. } else if (arg == "--llama2c-output-model") {
  691. if (++i >= argc) {
  692. invalid_param = true;
  693. break;
  694. }
  695. params->fn_llama2c_output_model = argv[i];
  696. } else if (arg == "-h" || arg == "--help") {
  697. print_usage(argc, argv, &default_params);
  698. exit(0);
  699. } else {
  700. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  701. print_usage(argc, argv, &default_params);
  702. exit(1);
  703. }
  704. }
  705. if (invalid_param) {
  706. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  707. print_usage(argc, argv, &default_params);
  708. exit(1);
  709. }
  710. if (!reqd_param_found){
  711. fprintf(stderr, "error: please specify a llama2.c .bin file to be converted with argument --llama2c-model\n");
  712. print_usage(argc, argv, &default_params);
  713. exit(1);
  714. }
  715. return true;
  716. }
  717. static std::string basename(const std::string &path) {
  718. size_t pos = path.find_last_of("/\\");
  719. if (pos == std::string::npos) {
  720. return path;
  721. }
  722. return path.substr(pos + 1);
  723. }
  724. int main(int argc, char ** argv) {
  725. struct train_params params = get_default_train_params();
  726. if (!params_parse(argc, argv, &params)) {
  727. return 1;
  728. }
  729. log_set_target(stdout);
  730. Config config;
  731. TransformerWeights weights = {};
  732. {
  733. LOG("%s: Loading llama2c model from %s\n", __func__, params.fn_llama2c_model);
  734. FILE * file = fopen(params.fn_llama2c_model, "rb");
  735. if (!file) {
  736. LOG("%s: Unable to open the checkpoint file %s!\n", __func__, params.fn_llama2c_model);
  737. return 1;
  738. }
  739. // read in the config header
  740. if (fread(&config, sizeof(Config), 1, file) != 1) {
  741. LOG("%s: Unable to read llama2c config from %s!\n",__func__,params.fn_llama2c_model);
  742. return 1;
  743. }
  744. auto shared_weights = config.vocab_size > 0;
  745. config.vocab_size = abs(config.vocab_size);
  746. // read in the Transformer weights
  747. alloc_weights(&weights, &config, shared_weights);
  748. if (checkpoint_init_weights(&weights, &config, file, shared_weights)) {
  749. LOG("%s: Unable to initialize transformer weights from %s!",__func__,params.fn_llama2c_model);
  750. return 1;
  751. }
  752. fclose(file);
  753. }
  754. struct llama_vocab vocab;
  755. load_vocab(params.fn_vocab_model, &config, &vocab);
  756. struct my_llama_model model;
  757. model.hparams.n_vocab = config.vocab_size; //llama_n_vocab(lctx);
  758. model.hparams.n_ctx = params.n_ctx;
  759. model.hparams.n_embd = config.dim; //params.n_embd;
  760. model.hparams.n_ff = config.hidden_dim;
  761. model.hparams.n_mult = 32;//params.n_mult;
  762. model.hparams.n_head = config.n_heads; //params.n_head;
  763. model.hparams.n_head_kv = config.n_kv_heads;
  764. model.hparams.n_layer = config.n_layers; //params.n_layer;
  765. model.hparams.n_rot = std::min((uint32_t)params.n_rotmax, model.hparams.n_embd / model.hparams.n_head);
  766. print_params(&model.hparams);
  767. struct ggml_init_params lcparams;
  768. lcparams.mem_size = 1024ll*1024ll*1024ll*((size_t) params.mem_model_gb);
  769. lcparams.mem_buffer = NULL;
  770. lcparams.no_alloc = false;
  771. model.ctx = ggml_init(lcparams);
  772. init_model(&model);
  773. model.name = basename(params.fn_llama2c_model);
  774. save_as_llama_model(&vocab, &model, &weights, params.fn_llama2c_output_model);
  775. LOG("%s: Saving llama.c model file %s in ggml format at %s\n", __func__, params.fn_llama2c_model, params.fn_llama2c_output_model);
  776. ggml_free(model.ctx);
  777. return 0;
  778. }