1
0

convert-llama2c-to-ggml.cpp 34 KB

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