model_loader.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #include <string>
  2. #include "model_loader.h"
  3. #define DEBUG_MODEL_LOAD 0
  4. std::ifstream open_ggml_file(const char* fname) {
  5. printf("%s: loading model from '%s'\n", __func__, fname);
  6. auto fin = std::ifstream(std::string(fname), std::ios::binary);
  7. if (!fin) {
  8. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname);
  9. throw std::invalid_argument("failed to open file."); // TODO Merge error message.
  10. }
  11. std::uint32_t magic;
  12. fin.read((char*)&magic, 4);
  13. if (magic != GGML_FILE_MAGIC) {
  14. fprintf(stderr, "%s: invalid model file '%s' (bad header %d)\n", __func__, fname, magic);
  15. throw std::invalid_argument("failed to open file."); // TODO Merge error message.
  16. }
  17. return fin;
  18. }
  19. void register_prefix(fairseq2_model &model, const std::string& name) {
  20. std::size_t i = name.find_last_of('.');
  21. while(i != std::string::npos && i > 0) {
  22. std::string prefix = name.substr(0, i);
  23. auto prev_tensor = model.tensors.find(prefix);
  24. if (prev_tensor != model.tensors.end()) {
  25. GGML_ASSERT(prev_tensor->second == nullptr);
  26. }
  27. model.tensors[prefix] = nullptr;
  28. i = name.find_last_of('.', i - 1);
  29. }
  30. }
  31. std::int64_t
  32. model_loader::load_model_weights(fairseq2_model &model, std::ifstream &fin)
  33. {
  34. std::int64_t num_tensor = 0;
  35. std::int64_t f32_tensor_size = 0;
  36. fin.read((char*) &num_tensor, sizeof(num_tensor));
  37. fin.read((char*) &f32_tensor_size, sizeof(f32_tensor_size));
  38. // TODO: it might be interesting to allow the caller to not upcast the weights to float32.
  39. // Note this require changing the on disk format
  40. bool as_float32 = true;
  41. struct ggml_init_params params = {
  42. /*.mem_size =*/ f32_tensor_size + num_tensor * (int64_t)ggml_tensor_overhead(),
  43. /*.mem_buffer =*/ NULL,
  44. /*.no_alloc =*/ false,
  45. };
  46. model.tensors_ctx = ggml_init(params);
  47. size_t model_size = 0;
  48. for (int i = 0; i < num_tensor; ++i) {
  49. std::string name = get_name(fin);
  50. if (name.length() == 0)
  51. break;
  52. auto tensor = load_tensor_value(fin, model.tensors_ctx, as_float32);
  53. if (tensor == nullptr) {
  54. // Abort in case of error, the input stream is corrupted at this point.
  55. printf("Error while reading tensor %s\n", name.c_str() );
  56. throw std::invalid_argument("Error while reading tensor from file.");
  57. }
  58. register_prefix(model, name);
  59. ggml_set_name(tensor, name.c_str());
  60. model.tensors[name] = tensor;
  61. if (DEBUG_MODEL_LOAD) {
  62. printf("%s [%5ld, %5ld], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), tensor->ne[0], tensor->ne[1], ggml_type_name(tensor->type), ggml_nbytes(tensor)/1024.0/1024.0, ggml_nbytes(tensor));
  63. }
  64. model_size += ggml_nbytes(tensor);
  65. }
  66. double mb = 1024.0 * 1024.0;
  67. printf("%s: model size: %8.2f MB, memory used: %8.2f MB, memory reserved: %8.2f MB\n",
  68. __func__,
  69. model_size / mb,
  70. ggml_used_mem(model.tensors_ctx) / mb,
  71. ggml_get_mem_size(model.tensors_ctx) / mb
  72. );
  73. return ggml_get_mem_size(model.tensors_ctx);
  74. }
  75. void assert_endianness() {
  76. union {
  77. unsigned int i;
  78. char c[4];
  79. } un;
  80. un.i = 0x12345678;
  81. if (un.c[0] == 0x78 && un.c[3] == 0x12) {
  82. printf("little-endian\n");
  83. }
  84. else if (un.c[0] == 0x12 && un.c[3] == 0x78) {
  85. printf("big-endian\n");
  86. GGML_ASSERT(false); // model_loader.cpp assumes the system is little-endian
  87. }
  88. else {
  89. printf("unknown-endian\n");
  90. GGML_ASSERT(false); // model_loader.cpp assumes the system is little-endian
  91. }
  92. }
  93. void model_loader::load_hparams(std::unordered_map<std::string, std::int64_t>& hparams, std::ifstream &fin)
  94. {
  95. std::int64_t num_params = 0;
  96. fin.read(reinterpret_cast<char*>(&num_params), sizeof num_params);
  97. GGML_ASSERT(fin.gcount() == 8);
  98. hparams.reserve(num_params);
  99. std::int64_t value;
  100. for (int i = 0; i < num_params; ++i) {
  101. std::string name = get_name(fin);
  102. if (name.length() == 0)
  103. break;
  104. fin.read((char*) &value, sizeof(value));
  105. hparams[name] = value;
  106. }
  107. }
  108. void model_loader::load_vocab(llama_vocab& vocab, std::ifstream &fin)
  109. {
  110. // vocab.special_bos_id = 1;
  111. // vocab.special_eos_id = 2;
  112. // vocab.special_unk_id = 0;
  113. // vocab.special_sep_id = -1;
  114. // vocab.special_pad_id = -1;
  115. std::int64_t vocab_size = 0;
  116. fin.read(reinterpret_cast<char*>(&vocab_size), sizeof(vocab_size));
  117. GGML_ASSERT(fin.gcount() == 8);
  118. vocab.token_to_id.reserve(vocab_size);
  119. vocab.id_to_token.reserve(vocab_size);
  120. std::string packed_vocab = get_name(fin);
  121. std::int64_t ctx_size = vocab_size * sizeof(float) + vocab_size + 2 * ggml_tensor_overhead();
  122. ctx_size *= 2;
  123. ggml_context* ctx = ggml_init(ggml_init_params{ctx_size, nullptr, false});
  124. ggml_tensor* lengths_tensor = load_tensor_value(fin, ctx, true);
  125. std::int8_t* lengths = (std::int8_t*)lengths_tensor->data;
  126. ggml_tensor* scores_tensor = load_tensor_value(fin, ctx, true);
  127. float* scores = ggml_get_data_f32(scores_tensor);
  128. int64_t offset = 0;
  129. for (int i = 0; i < vocab_size; ++i) {
  130. // TODO: we should use string view instead of copying each word in a new string
  131. std::string word = packed_vocab.substr(offset, lengths[i]);
  132. vocab.token_to_id[word] = i;
  133. vocab.id_to_token.push_back({word, scores[i], LLAMA_TOKEN_TYPE_NORMAL});
  134. offset += lengths[i] + 1;
  135. }
  136. // Since we copied lengths and scores, we don't need the context anymore.
  137. ggml_free(ctx);
  138. // vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  139. // TODO: special tokens stuff ?
  140. }
  141. ggml_tensor* load_tensor_value(std::ifstream &fin, ggml_context* ctx, bool as_float32)
  142. {
  143. int32_t n_dims = 0;
  144. int32_t raw_type = 0;
  145. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  146. fin.read(reinterpret_cast<char *>(&raw_type), sizeof(raw_type));
  147. ggml_type type = ggml_type(raw_type);
  148. if (n_dims <= 0 || n_dims > GGML_MAX_DIMS || raw_type < 0 || raw_type > GGML_TYPE_COUNT) {
  149. return nullptr;
  150. }
  151. int64_t ne[4] = {1, 1, 1, 1};
  152. for (int i = 0; i < n_dims; ++i) {
  153. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  154. }
  155. ggml_tensor* tensor;
  156. if (as_float32 && type == GGML_TYPE_F16) {
  157. // read quantized weights from disk, and convert them to f32.
  158. tensor = ggml_new_tensor(ctx, GGML_TYPE_F32, n_dims, ne);
  159. ggml_fp16_t buf[128];
  160. int num_el = ggml_nelements(tensor);
  161. for (int i = 0; i < num_el; i += 128) {
  162. int block_size = std::min(128, num_el - i);
  163. fin.read(reinterpret_cast<char *>(&buf), ggml_type_size(type) * block_size);
  164. ggml_fp16_to_fp32_row((const ggml_fp16_t*)&buf, (float*)tensor->data + i, block_size);
  165. }
  166. } else {
  167. tensor = ggml_new_tensor(ctx, type, n_dims, ne);
  168. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  169. }
  170. return tensor;
  171. }
  172. std::string
  173. model_loader::get_name(std::ifstream& fin)
  174. {
  175. std::uint32_t length = 0;
  176. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  177. if (length == 0)
  178. return "";
  179. std::string name(length, 0);
  180. fin.read(&name[0], length);
  181. return name;
  182. }
  183. extern "C" int load_fairseq2_ggml_file(fairseq2_model& model, const char* fname) {
  184. model_loader loader;
  185. assert_endianness();
  186. auto fin = open_ggml_file(fname);
  187. loader.load_hparams(model.hparams, fin);
  188. loader.load_hparams(model.layer_config, fin);
  189. loader.load_vocab(model.vocab, fin);
  190. loader.load_model_weights(model, fin);
  191. return 0;
  192. }