1
0

convert-llama2c-to-ggml.cpp 35 KB

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