gguf.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. #include "ggml.h"
  2. #include "ggml-backend.h"
  3. #include "ggml-impl.h"
  4. #include "gguf.h"
  5. #include <cinttypes>
  6. #include <cstddef>
  7. #include <cstdint>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <map>
  12. #include <new>
  13. #include <stdexcept>
  14. #include <string>
  15. #include <vector>
  16. template <typename T>
  17. struct type_to_gguf_type;
  18. template <>
  19. struct type_to_gguf_type<uint8_t> {
  20. static constexpr enum gguf_type value = GGUF_TYPE_UINT8;
  21. };
  22. template <>
  23. struct type_to_gguf_type<int8_t> {
  24. static constexpr enum gguf_type value = GGUF_TYPE_INT8;
  25. };
  26. template <>
  27. struct type_to_gguf_type<uint16_t> {
  28. static constexpr enum gguf_type value = GGUF_TYPE_UINT16;
  29. };
  30. template <>
  31. struct type_to_gguf_type<int16_t> {
  32. static constexpr enum gguf_type value = GGUF_TYPE_INT16;
  33. };
  34. template <>
  35. struct type_to_gguf_type<uint32_t> {
  36. static constexpr enum gguf_type value = GGUF_TYPE_UINT32;
  37. };
  38. template <>
  39. struct type_to_gguf_type<int32_t> {
  40. static constexpr enum gguf_type value = GGUF_TYPE_INT32;
  41. };
  42. template <>
  43. struct type_to_gguf_type<float> {
  44. static constexpr enum gguf_type value = GGUF_TYPE_FLOAT32;
  45. };
  46. template <>
  47. struct type_to_gguf_type<bool> {
  48. static constexpr enum gguf_type value = GGUF_TYPE_BOOL;
  49. };
  50. template <>
  51. struct type_to_gguf_type<std::string> {
  52. static constexpr enum gguf_type value = GGUF_TYPE_STRING;
  53. };
  54. template <>
  55. struct type_to_gguf_type<uint64_t> {
  56. static constexpr enum gguf_type value = GGUF_TYPE_UINT64;
  57. };
  58. template <>
  59. struct type_to_gguf_type<int64_t> {
  60. static constexpr enum gguf_type value = GGUF_TYPE_INT64;
  61. };
  62. template <>
  63. struct type_to_gguf_type<double> {
  64. static constexpr enum gguf_type value = GGUF_TYPE_FLOAT64;
  65. };
  66. static const std::map<gguf_type, size_t> GGUF_TYPE_SIZE = {
  67. {GGUF_TYPE_UINT8, sizeof(uint8_t)},
  68. {GGUF_TYPE_INT8, sizeof(int8_t)},
  69. {GGUF_TYPE_UINT16, sizeof(uint16_t)},
  70. {GGUF_TYPE_INT16, sizeof(int16_t)},
  71. {GGUF_TYPE_UINT32, sizeof(uint32_t)},
  72. {GGUF_TYPE_INT32, sizeof(int32_t)},
  73. {GGUF_TYPE_FLOAT32, sizeof(float)},
  74. {GGUF_TYPE_BOOL, sizeof(int8_t)},
  75. {GGUF_TYPE_STRING, 0}, // undefined
  76. {GGUF_TYPE_ARRAY, 0}, // undefined
  77. {GGUF_TYPE_UINT64, sizeof(uint64_t)},
  78. {GGUF_TYPE_INT64, sizeof(int64_t)},
  79. {GGUF_TYPE_FLOAT64, sizeof(double)},
  80. };
  81. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  82. static const std::map<gguf_type, const char *> GGUF_TYPE_NAME = {
  83. {GGUF_TYPE_UINT8, "u8"},
  84. {GGUF_TYPE_INT8, "i8"},
  85. {GGUF_TYPE_UINT16, "u16"},
  86. {GGUF_TYPE_INT16, "i16"},
  87. {GGUF_TYPE_UINT32, "u32"},
  88. {GGUF_TYPE_INT32, "i32"},
  89. {GGUF_TYPE_FLOAT32, "f32"},
  90. {GGUF_TYPE_BOOL, "bool"},
  91. {GGUF_TYPE_STRING, "str"},
  92. {GGUF_TYPE_ARRAY, "arr"},
  93. {GGUF_TYPE_UINT64, "u64"},
  94. {GGUF_TYPE_INT64, "i64"},
  95. {GGUF_TYPE_FLOAT64, "f64"},
  96. };
  97. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  98. size_t gguf_type_size(enum gguf_type type) {
  99. auto it = GGUF_TYPE_SIZE.find(type);
  100. return it == GGUF_TYPE_SIZE.end() ? 0 : it->second;
  101. }
  102. struct gguf_kv {
  103. std::string key;
  104. bool is_array;
  105. enum gguf_type type;
  106. std::vector<int8_t> data;
  107. std::vector<std::string> data_string;
  108. template <typename T>
  109. gguf_kv(const std::string & key, const T value)
  110. : key(key), is_array(false), type(type_to_gguf_type<T>::value) {
  111. GGML_ASSERT(!key.empty());
  112. data.resize(sizeof(T));
  113. memcpy(data.data(), &value, sizeof(T));
  114. }
  115. template <typename T>
  116. gguf_kv(const std::string & key, const std::vector<T> & value)
  117. : key(key), is_array(true), type(type_to_gguf_type<T>::value) {
  118. GGML_ASSERT(!key.empty());
  119. data.resize(value.size()*sizeof(T));
  120. for (size_t i = 0; i < value.size(); ++i) {
  121. const T tmp = value[i];
  122. memcpy(data.data() + i*sizeof(T), &tmp, sizeof(T));
  123. }
  124. }
  125. gguf_kv(const std::string & key, const std::string & value)
  126. : key(key), is_array(false), type(GGUF_TYPE_STRING) {
  127. GGML_ASSERT(!key.empty());
  128. data_string.push_back(value);
  129. }
  130. gguf_kv(const std::string & key, const std::vector<std::string> & value)
  131. : key(key), is_array(true), type(GGUF_TYPE_STRING) {
  132. GGML_ASSERT(!key.empty());
  133. data_string = value;
  134. }
  135. const std::string & get_key() const {
  136. return key;
  137. }
  138. const enum gguf_type & get_type() const {
  139. return type;
  140. }
  141. size_t get_ne() const {
  142. if (type == GGUF_TYPE_STRING) {
  143. const size_t ne = data_string.size();
  144. GGML_ASSERT(is_array || ne == 1);
  145. return ne;
  146. }
  147. const size_t type_size = gguf_type_size(type);
  148. GGML_ASSERT(data.size() % type_size == 0);
  149. const size_t ne = data.size() / type_size;
  150. GGML_ASSERT(is_array || ne == 1);
  151. return ne;
  152. }
  153. template <typename T>
  154. const T & get_val(const size_t i = 0) const {
  155. GGML_ASSERT(type_to_gguf_type<T>::value == type);
  156. if constexpr (std::is_same<T, std::string>::value) {
  157. GGML_ASSERT(data_string.size() >= i+1);
  158. return data_string[i];
  159. }
  160. const size_t type_size = gguf_type_size(type);
  161. GGML_ASSERT(data.size() % type_size == 0);
  162. GGML_ASSERT(data.size() >= (i+1)*type_size);
  163. return reinterpret_cast<const T *>(data.data())[i];
  164. }
  165. void cast(const enum gguf_type new_type) {
  166. const size_t new_type_size = gguf_type_size(new_type);
  167. GGML_ASSERT(data.size() % new_type_size == 0);
  168. type = new_type;
  169. }
  170. };
  171. struct gguf_tensor_info {
  172. struct ggml_tensor t; // for holding the equivalent info
  173. uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
  174. };
  175. struct gguf_context {
  176. uint32_t version = GGUF_VERSION;
  177. std::vector<struct gguf_kv> kv;
  178. std::vector<struct gguf_tensor_info> info;
  179. size_t alignment = GGUF_DEFAULT_ALIGNMENT;
  180. size_t offset = 0; // offset of `data` from beginning of file
  181. size_t size = 0; // size of `data` in bytes
  182. void * data = nullptr;
  183. };
  184. struct gguf_reader {
  185. FILE * file;
  186. gguf_reader(FILE * file) : file(file) {}
  187. template <typename T>
  188. bool read(T & dst) const {
  189. return fread(&dst, 1, sizeof(dst), file) == sizeof(dst);
  190. }
  191. template <typename T>
  192. bool read(std::vector<T> & dst, const size_t n) const {
  193. dst.resize(n);
  194. for (size_t i = 0; i < dst.size(); ++i) {
  195. if constexpr (std::is_same<T, bool>::value) {
  196. bool tmp;
  197. if (!read(tmp)) {
  198. return false;
  199. }
  200. dst[i] = tmp;
  201. } else {
  202. if (!read(dst[i])) {
  203. return false;
  204. }
  205. }
  206. }
  207. return true;
  208. }
  209. bool read(bool & dst) const {
  210. int8_t tmp = -1;
  211. if (!read(tmp)) {
  212. return false;
  213. }
  214. dst = tmp != 0;
  215. return true;
  216. }
  217. bool read(enum ggml_type & dst) const {
  218. int32_t tmp = -1;
  219. if (!read(tmp)) {
  220. return false;
  221. }
  222. dst = ggml_type(tmp);
  223. return true;
  224. }
  225. bool read(enum gguf_type & dst) const {
  226. int32_t tmp = -1;
  227. if (!read(tmp)) {
  228. return false;
  229. }
  230. dst = gguf_type(tmp);
  231. return true;
  232. }
  233. bool read(std::string & dst) const {
  234. uint64_t size = -1;
  235. if (!read(size)) {
  236. return false;
  237. }
  238. dst.resize(size);
  239. return fread(dst.data(), 1, dst.length(), file) == dst.length();
  240. }
  241. bool read(void * dst, const size_t size) const {
  242. return fread(dst, 1, size, file) == size;
  243. }
  244. };
  245. struct gguf_context * gguf_init_empty(void) {
  246. return new gguf_context;
  247. }
  248. template<typename T>
  249. bool gguf_read_emplace_helper(const struct gguf_reader & gr, std::vector<struct gguf_kv> & kv, const std::string & key, const bool is_array, const size_t n) {
  250. if (is_array) {
  251. std::vector<T> value;
  252. try {
  253. if (!gr.read(value, n)) {
  254. return false;
  255. }
  256. } catch (std::length_error &) {
  257. fprintf(stderr, "%s: encountered length_error while reading value for key '%s'\n", __func__, key.c_str());
  258. return false;
  259. } catch (std::bad_alloc &) {
  260. fprintf(stderr, "%s: encountered bad_alloc error while reading value for key '%s'\n", __func__, key.c_str());
  261. return false;
  262. }
  263. kv.emplace_back(key, value);
  264. } else {
  265. T value;
  266. if (!gr.read(value)) {
  267. return false;
  268. }
  269. kv.emplace_back(key, value);
  270. }
  271. return true;
  272. }
  273. struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params) {
  274. const struct gguf_reader gr(file);
  275. struct gguf_context * ctx = new gguf_context;
  276. bool ok = true;
  277. // file magic
  278. {
  279. std::vector<char> magic;
  280. ok = ok && gr.read(magic, 4);
  281. if (!ok) {
  282. fprintf(stderr, "%s: failed to read magic\n", __func__);
  283. gguf_free(ctx);
  284. return nullptr;
  285. }
  286. for (uint32_t i = 0; i < magic.size(); i++) {
  287. if (magic[i] != GGUF_MAGIC[i]) {
  288. fprintf(stderr, "%s: invalid magic characters: '%c%c%c%c', expected 'GGUF'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
  289. gguf_free(ctx);
  290. return nullptr;
  291. }
  292. }
  293. }
  294. // header
  295. int64_t n_kv = 0;
  296. int64_t n_tensors = 0;
  297. if (ok && gr.read(ctx->version)) {
  298. if (ctx->version == 1) {
  299. fprintf(stderr, "%s: GGUFv1 is no longer supported, please use a more up-to-date version\n", __func__);
  300. ok = false;
  301. }
  302. if (ctx->version > GGUF_VERSION) {
  303. fprintf(stderr, "%s: this GGUF file is version %" PRIu32 " but this software only supports up to version %d\n",
  304. __func__, ctx->version, GGUF_VERSION);
  305. ok = false;
  306. }
  307. } else {
  308. ok = false;
  309. }
  310. if (ok && gr.read(n_tensors)) {
  311. static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
  312. if (n_tensors < 0 || n_tensors > int64_t(SIZE_MAX/sizeof(gguf_tensor_info))) {
  313. fprintf(stderr, "%s: number of tensors is %" PRIi64 " but must be in [0, %zu]\n",
  314. __func__, n_tensors, SIZE_MAX/sizeof(gguf_tensor_info));
  315. ok = false;
  316. }
  317. } else {
  318. ok = false;
  319. }
  320. if (ok && gr.read(n_kv)) {
  321. static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
  322. if (n_kv < 0 || n_kv > int64_t(SIZE_MAX/sizeof(gguf_kv))) {
  323. fprintf(stderr, "%s: number of key value pairs is %" PRIi64 " but must be in [0, %zu]\n",
  324. __func__, n_kv, SIZE_MAX/sizeof(gguf_kv));
  325. ok = false;
  326. }
  327. } else {
  328. ok = false;
  329. }
  330. if (!ok) {
  331. fprintf(stderr, "%s: failed to read header\n", __func__);
  332. gguf_free(ctx);
  333. return nullptr;
  334. }
  335. // KV pairs
  336. {
  337. for (int64_t i = 0; ok && i < n_kv; ++i) {
  338. std::string key;
  339. gguf_type type = gguf_type(-1);
  340. bool is_array = false;
  341. uint64_t n = 1;
  342. try {
  343. ok = ok && gr.read(key);
  344. } catch (std::length_error &) {
  345. fprintf(stderr, "%s: encountered length_error while reading key %" PRIi64 "\n", __func__, i);
  346. ok = false;
  347. } catch (std::bad_alloc &) {
  348. fprintf(stderr, "%s: encountered bad_alloc error while reading key %" PRIi64 "\n", __func__, i);
  349. ok = false;
  350. }
  351. for (size_t j = 0; ok && j < ctx->kv.size(); ++j) {
  352. if (key == ctx->kv[j].key) {
  353. fprintf(stderr, "%s: duplicate key '%s' for tensors %zu and %" PRIi64 " \n", __func__, key.c_str(), j, i);
  354. ok = false;
  355. }
  356. }
  357. if (!ok) {
  358. break;
  359. }
  360. ok = ok && gr.read(type);
  361. if (type == GGUF_TYPE_ARRAY) {
  362. is_array = true;
  363. ok = ok && gr.read(type);
  364. ok = ok && gr.read(n);
  365. }
  366. if (!ok) {
  367. break;
  368. }
  369. switch (type) {
  370. case GGUF_TYPE_UINT8: ok = ok && gguf_read_emplace_helper<uint8_t> (gr, ctx->kv, key, is_array, n); break;
  371. case GGUF_TYPE_INT8: ok = ok && gguf_read_emplace_helper<int8_t> (gr, ctx->kv, key, is_array, n); break;
  372. case GGUF_TYPE_UINT16: ok = ok && gguf_read_emplace_helper<uint16_t> (gr, ctx->kv, key, is_array, n); break;
  373. case GGUF_TYPE_INT16: ok = ok && gguf_read_emplace_helper<int16_t> (gr, ctx->kv, key, is_array, n); break;
  374. case GGUF_TYPE_UINT32: ok = ok && gguf_read_emplace_helper<uint32_t> (gr, ctx->kv, key, is_array, n); break;
  375. case GGUF_TYPE_INT32: ok = ok && gguf_read_emplace_helper<int32_t> (gr, ctx->kv, key, is_array, n); break;
  376. case GGUF_TYPE_FLOAT32: ok = ok && gguf_read_emplace_helper<float> (gr, ctx->kv, key, is_array, n); break;
  377. case GGUF_TYPE_BOOL: ok = ok && gguf_read_emplace_helper<bool> (gr, ctx->kv, key, is_array, n); break;
  378. case GGUF_TYPE_STRING: ok = ok && gguf_read_emplace_helper<std::string>(gr, ctx->kv, key, is_array, n); break;
  379. case GGUF_TYPE_UINT64: ok = ok && gguf_read_emplace_helper<uint64_t> (gr, ctx->kv, key, is_array, n); break;
  380. case GGUF_TYPE_INT64: ok = ok && gguf_read_emplace_helper<int64_t> (gr, ctx->kv, key, is_array, n); break;
  381. case GGUF_TYPE_FLOAT64: ok = ok && gguf_read_emplace_helper<double> (gr, ctx->kv, key, is_array, n); break;
  382. case GGUF_TYPE_ARRAY:
  383. default:
  384. {
  385. fprintf(stderr, "%s: key '%s' has invalid GGUF type %d\n", __func__, key.c_str(), type);
  386. ok = false;
  387. } break;
  388. }
  389. }
  390. if (!ok) {
  391. fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
  392. gguf_free(ctx);
  393. return nullptr;
  394. }
  395. GGML_ASSERT(int64_t(ctx->kv.size()) == n_kv);
  396. const int alignment_idx = gguf_find_key(ctx, GGUF_KEY_GENERAL_ALIGNMENT);
  397. ctx->alignment = alignment_idx == -1 ? GGUF_DEFAULT_ALIGNMENT : gguf_get_val_u32(ctx, alignment_idx);
  398. if (ctx->alignment == 0 || (ctx->alignment & (ctx->alignment - 1)) != 0) {
  399. fprintf(stderr, "%s: alignment %zu is not a power of 2\n", __func__, ctx->alignment);
  400. gguf_free(ctx);
  401. return nullptr;
  402. }
  403. }
  404. // read the tensor info
  405. for (int64_t i = 0; ok && i < n_tensors; ++i) {
  406. struct gguf_tensor_info info;
  407. // tensor name
  408. {
  409. std::string name;
  410. try {
  411. ok = ok && gr.read(name);
  412. } catch (std::length_error &) {
  413. fprintf(stderr, "%s: encountered length_error while reading tensor name %" PRIi64 "\n", __func__, i);
  414. ok = false;
  415. } catch (std::bad_alloc &) {
  416. fprintf(stderr, "%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
  417. ok = false;
  418. }
  419. if (name.length() >= GGML_MAX_NAME) {
  420. fprintf(stderr, "%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
  421. ok = false;
  422. break;
  423. }
  424. ggml_set_name(&info.t, name.c_str());
  425. // make sure there are no duplicate tensor names
  426. for (int64_t j = 0; ok && j < i; ++j) {
  427. if (strcmp(info.t.name, ctx->info[j].t.name) == 0) {
  428. fprintf(stderr, "%s: duplicate tensor name '%s' for tensors %" PRIi64 " and %" PRIi64 "\n", __func__, info.t.name, j, i);
  429. ok = false;
  430. break;
  431. }
  432. }
  433. }
  434. if (!ok) {
  435. break;
  436. }
  437. // tensor shape
  438. {
  439. uint32_t n_dims = -1;
  440. ok = ok && gr.read(n_dims);
  441. if (n_dims > GGML_MAX_DIMS) {
  442. fprintf(stderr, "%s: tensor '%s' has invalid number of dimensions: %" PRIu32 " > %" PRIu32 "\n",
  443. __func__, info.t.name, n_dims, GGML_MAX_DIMS);
  444. ok = false;
  445. break;
  446. }
  447. for (uint32_t j = 0; ok && j < GGML_MAX_DIMS; ++j) {
  448. info.t.ne[j] = 1;
  449. if (j < n_dims) {
  450. ok = ok && gr.read(info.t.ne[j]);
  451. }
  452. // check that all ne are non-negative
  453. if (info.t.ne[j] < 0) {
  454. fprintf(stderr, "%s: tensor '%s' dimension %" PRIu32 " has invalid number of elements: %" PRIi64 " < 0\n",
  455. __func__, info.t.name, j, info.t.ne[j]);
  456. ok = false;
  457. break;
  458. }
  459. }
  460. // check that the total number of elements is representable
  461. if (ok && ((INT64_MAX/info.t.ne[1] <= info.t.ne[0]) ||
  462. (INT64_MAX/info.t.ne[2] <= info.t.ne[0]*info.t.ne[1]) ||
  463. (INT64_MAX/info.t.ne[3] <= info.t.ne[0]*info.t.ne[1]*info.t.ne[2]))) {
  464. fprintf(stderr, "%s: total number of elements in tensor '%s' with shape "
  465. "(%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") is >= %" PRIi64 "\n",
  466. __func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], INT64_MAX);
  467. ok = false;
  468. break;
  469. }
  470. }
  471. if (!ok) {
  472. break;
  473. }
  474. // tensor type
  475. {
  476. ok = ok && gr.read(info.t.type);
  477. // check that tensor type is within defined range
  478. if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
  479. fprintf(stderr, "%s: tensor '%s' has invalid ggml type %d (%s)\n",
  480. __func__, info.t.name, info.t.type, ggml_type_name(info.t.type));
  481. ok = false;
  482. break;
  483. }
  484. const size_t type_size = ggml_type_size(info.t.type);
  485. const int64_t blck_size = ggml_blck_size(info.t.type);
  486. // check that row size is divisible by block size
  487. if (blck_size == 0 || info.t.ne[0] % blck_size != 0) {
  488. fprintf(stderr, "%s: tensor '%s' of type %d (%s) has %" PRId64 " elements per row, "
  489. "not a multiple of block size (%" PRId64 ")\n",
  490. __func__, info.t.name, (int) info.t.type, ggml_type_name(info.t.type), info.t.ne[0], blck_size);
  491. ok = false;
  492. break;
  493. }
  494. // calculate byte offsets given the tensor shape and type
  495. info.t.nb[0] = type_size;
  496. info.t.nb[1] = info.t.nb[0]*(info.t.ne[0]/blck_size);
  497. for (int j = 2; j < GGML_MAX_DIMS; ++j) {
  498. info.t.nb[j] = info.t.nb[j - 1]*info.t.ne[j - 1];
  499. }
  500. }
  501. if (!ok) {
  502. break;
  503. }
  504. // tensor data offset within buffer
  505. ok = ok && gr.read(info.offset);
  506. ctx->info.push_back(info);
  507. }
  508. if (!ok) {
  509. fprintf(stderr, "%s: failed to read tensor info\n", __func__);
  510. gguf_free(ctx);
  511. return nullptr;
  512. }
  513. GGML_ASSERT(int64_t(ctx->info.size()) == n_tensors);
  514. // we require the data section to be aligned, so take into account any padding
  515. if (fseek(file, GGML_PAD(ftell(file), ctx->alignment), SEEK_SET) != 0) {
  516. fprintf(stderr, "%s: failed to seek to beginning of data section\n", __func__);
  517. gguf_free(ctx);
  518. return nullptr;
  519. }
  520. // store the current file offset - this is where the data section starts
  521. ctx->offset = ftell(file);
  522. // compute the total size of the data section, taking into account the alignment
  523. {
  524. ctx->size = 0;
  525. for (size_t i = 0; i < ctx->info.size(); ++i) {
  526. const gguf_tensor_info & ti = ctx->info[i];
  527. if (ti.offset != ctx->size) {
  528. fprintf(stderr, "%s: tensor '%s' has offset %" PRIu64 ", expected %zu\n",
  529. __func__, ti.t.name, ti.offset, ctx->size);
  530. fprintf(stderr, "%s: failed to read tensor data\n", __func__);
  531. gguf_free(ctx);
  532. return nullptr;
  533. }
  534. ctx->size += GGML_PAD(ggml_nbytes(&ti.t), ctx->alignment);
  535. }
  536. }
  537. // load the tensor data only if requested
  538. if (params.ctx != nullptr) {
  539. // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
  540. // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
  541. // the ggml_tensor structs to the appropriate locations in the binary blob
  542. // compute the exact size needed for the new ggml_context
  543. const size_t mem_size =
  544. params.no_alloc ?
  545. (n_tensors )*ggml_tensor_overhead() :
  546. (n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
  547. struct ggml_init_params pdata = {
  548. /*mem_size =*/ mem_size,
  549. /*mem_buffer =*/ nullptr,
  550. /*no_alloc =*/ params.no_alloc,
  551. };
  552. *params.ctx = ggml_init(pdata);
  553. if (*params.ctx == nullptr) {
  554. fprintf(stderr, "%s: failed to initialize ggml context for storing tensors\n", __func__);
  555. gguf_free(ctx);
  556. return nullptr;
  557. }
  558. struct ggml_context * ctx_data = *params.ctx;
  559. struct ggml_tensor * data = nullptr;
  560. if (!params.no_alloc) {
  561. data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
  562. ok = ok && data != nullptr;
  563. if (ok) {
  564. ggml_set_name(data, "GGUF tensor data binary blob");
  565. }
  566. // read the binary blob with the tensor data
  567. ok = ok && gr.read(data->data, ctx->size);
  568. if (!ok) {
  569. fprintf(stderr, "%s: failed to read tensor data binary blob\n", __func__);
  570. ggml_free(ctx_data);
  571. *params.ctx = nullptr;
  572. gguf_free(ctx);
  573. return nullptr;
  574. }
  575. ctx->data = data->data;
  576. }
  577. ggml_set_no_alloc(ctx_data, true);
  578. // create the tensors
  579. for (size_t i = 0; i < ctx->info.size(); ++i) {
  580. const struct gguf_tensor_info & info = ctx->info[i];
  581. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
  582. ok = ok && cur != nullptr;
  583. if (!ok) {
  584. break;
  585. }
  586. ggml_set_name(cur, info.t.name);
  587. // point the data member to the appropriate location in the binary blob using the tensor info
  588. if (!params.no_alloc) {
  589. cur->data = (char *) data->data + info.offset;
  590. }
  591. }
  592. if (!ok) {
  593. fprintf(stderr, "%s: failed to create tensors\n", __func__);
  594. ggml_free(ctx_data);
  595. *params.ctx = nullptr;
  596. gguf_free(ctx);
  597. return nullptr;
  598. }
  599. ggml_set_no_alloc(ctx_data, params.no_alloc);
  600. }
  601. return ctx;
  602. }
  603. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  604. FILE * file = ggml_fopen(fname, "rb");
  605. if (!file) {
  606. fprintf(stderr, "%s: failed to open GGUF file '%s'\n", __func__, fname);
  607. return nullptr;
  608. }
  609. struct gguf_context * result = gguf_init_from_file_impl(file, params);
  610. fclose(file);
  611. return result;
  612. }
  613. void gguf_free(struct gguf_context * ctx) {
  614. if (ctx == nullptr) {
  615. return;
  616. }
  617. delete ctx;
  618. }
  619. const char * gguf_type_name(enum gguf_type type) {
  620. auto it = GGUF_TYPE_NAME.find(type);
  621. return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
  622. }
  623. uint32_t gguf_get_version(const struct gguf_context * ctx) {
  624. return ctx->version;
  625. }
  626. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  627. return ctx->alignment;
  628. }
  629. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  630. return ctx->offset;
  631. }
  632. int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
  633. return ctx->kv.size();
  634. }
  635. int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
  636. // return -1 if key not found
  637. int64_t keyfound = -1;
  638. const int64_t n_kv = gguf_get_n_kv(ctx);
  639. for (int64_t i = 0; i < n_kv; ++i) {
  640. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  641. keyfound = i;
  642. break;
  643. }
  644. }
  645. return keyfound;
  646. }
  647. const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
  648. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  649. return ctx->kv[key_id].get_key().c_str();
  650. }
  651. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
  652. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  653. return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
  654. }
  655. enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id) {
  656. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  657. GGML_ASSERT(ctx->kv[key_id].is_array);
  658. return ctx->kv[key_id].get_type();
  659. }
  660. const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id) {
  661. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  662. GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
  663. return ctx->kv[key_id].data.data();
  664. }
  665. const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
  666. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  667. GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
  668. return ctx->kv[key_id].data_string[i].c_str();
  669. }
  670. size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
  671. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  672. if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
  673. return ctx->kv[key_id].data_string.size();
  674. }
  675. const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
  676. GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
  677. return ctx->kv[key_id].data.size() / type_size;
  678. }
  679. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
  680. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  681. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  682. return ctx->kv[key_id].get_val<uint8_t>();
  683. }
  684. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
  685. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  686. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  687. return ctx->kv[key_id].get_val<int8_t>();
  688. }
  689. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
  690. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  691. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  692. return ctx->kv[key_id].get_val<uint16_t>();
  693. }
  694. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
  695. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  696. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  697. return ctx->kv[key_id].get_val<int16_t>();
  698. }
  699. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
  700. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  701. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  702. return ctx->kv[key_id].get_val<uint32_t>();
  703. }
  704. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
  705. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  706. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  707. return ctx->kv[key_id].get_val<int32_t>();
  708. }
  709. float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
  710. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  711. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  712. return ctx->kv[key_id].get_val<float>();
  713. }
  714. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
  715. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  716. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  717. return ctx->kv[key_id].get_val<uint64_t>();
  718. }
  719. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
  720. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  721. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  722. return ctx->kv[key_id].get_val<int64_t>();
  723. }
  724. double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
  725. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  726. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  727. return ctx->kv[key_id].get_val<double>();
  728. }
  729. bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
  730. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  731. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  732. return ctx->kv[key_id].get_val<bool>();
  733. }
  734. const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
  735. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  736. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  737. return ctx->kv[key_id].get_val<std::string>().c_str();
  738. }
  739. const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
  740. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  741. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  742. GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
  743. return ctx->kv[key_id].data.data();
  744. }
  745. int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
  746. return ctx->info.size();
  747. }
  748. int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  749. // return -1 if tensor not found
  750. int64_t tensor_id = -1;
  751. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  752. for (int64_t i = 0; i < n_tensors; ++i) {
  753. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  754. tensor_id = i;
  755. break;
  756. }
  757. }
  758. return tensor_id;
  759. }
  760. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
  761. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  762. return ctx->info[tensor_id].offset;
  763. }
  764. const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
  765. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  766. return ctx->info[tensor_id].t.name;
  767. }
  768. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
  769. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  770. return ctx->info[tensor_id].t.type;
  771. }
  772. size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
  773. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  774. return ggml_nbytes(&ctx->info[tensor_id].t);
  775. }
  776. int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
  777. const int64_t key_id = gguf_find_key(ctx, key);
  778. if (key_id >= 0) {
  779. ctx->kv.erase(ctx->kv.begin() + key_id);
  780. }
  781. return key_id;
  782. }
  783. template<typename T>
  784. static void gguf_check_reserved_keys(const std::string & key, const T val) {
  785. if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
  786. if constexpr (std::is_same<T, uint32_t>::value) {
  787. GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
  788. } else {
  789. GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
  790. }
  791. }
  792. }
  793. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
  794. gguf_check_reserved_keys(key, val);
  795. gguf_remove_key(ctx, key);
  796. ctx->kv.emplace_back(key, val);
  797. }
  798. void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
  799. gguf_check_reserved_keys(key, val);
  800. gguf_remove_key(ctx, key);
  801. ctx->kv.emplace_back(key, val);
  802. }
  803. void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
  804. gguf_check_reserved_keys(key, val);
  805. gguf_remove_key(ctx, key);
  806. ctx->kv.emplace_back(key, val);
  807. }
  808. void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
  809. gguf_check_reserved_keys(key, val);
  810. gguf_remove_key(ctx, key);
  811. ctx->kv.emplace_back(key, val);
  812. }
  813. void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
  814. gguf_check_reserved_keys(key, val);
  815. gguf_remove_key(ctx, key);
  816. ctx->kv.emplace_back(key, val);
  817. }
  818. void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  819. gguf_check_reserved_keys(key, val);
  820. gguf_remove_key(ctx, key);
  821. ctx->kv.emplace_back(key, val);
  822. }
  823. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  824. gguf_check_reserved_keys(key, val);
  825. gguf_remove_key(ctx, key);
  826. ctx->kv.emplace_back(key, val);
  827. }
  828. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  829. gguf_check_reserved_keys(key, val);
  830. gguf_remove_key(ctx, key);
  831. ctx->kv.emplace_back(key, val);
  832. }
  833. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  834. gguf_check_reserved_keys(key, val);
  835. gguf_remove_key(ctx, key);
  836. ctx->kv.emplace_back(key, val);
  837. }
  838. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  839. gguf_check_reserved_keys(key, val);
  840. gguf_remove_key(ctx, key);
  841. ctx->kv.emplace_back(key, val);
  842. }
  843. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  844. gguf_check_reserved_keys(key, val);
  845. gguf_remove_key(ctx, key);
  846. ctx->kv.emplace_back(key, val);
  847. }
  848. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  849. gguf_check_reserved_keys(key, val);
  850. gguf_remove_key(ctx, key);
  851. ctx->kv.emplace_back(key, std::string(val));
  852. }
  853. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n) {
  854. gguf_check_reserved_keys(key, data);
  855. gguf_remove_key(ctx, key);
  856. const size_t nbytes = n*gguf_type_size(type);
  857. std::vector<int8_t> tmp(nbytes);
  858. if (!tmp.empty()) {
  859. memcpy(tmp.data(), data, nbytes);
  860. }
  861. ctx->kv.emplace_back(key, tmp);
  862. ctx->kv.back().cast(type);
  863. }
  864. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, size_t n) {
  865. gguf_check_reserved_keys(key, data);
  866. gguf_remove_key(ctx, key);
  867. std::vector<std::string> tmp(n);
  868. for (size_t i = 0; i < n; ++i) {
  869. tmp[i] = data[i];
  870. }
  871. ctx->kv.emplace_back(key, tmp);
  872. }
  873. // set or add KV pairs from another context
  874. void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src) {
  875. const int64_t n_kv = gguf_get_n_kv(src);
  876. for (int64_t i = 0; i < n_kv; ++i) {
  877. const struct gguf_kv & kv = src->kv[i];
  878. if (!kv.is_array) {
  879. switch (kv.get_type()) {
  880. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, kv.get_key().c_str(), kv.get_val<uint8_t>()); break;
  881. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, kv.get_key().c_str(), kv.get_val<int8_t>()); break;
  882. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, kv.get_key().c_str(), kv.get_val<uint16_t>()); break;
  883. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, kv.get_key().c_str(), kv.get_val<int16_t>()); break;
  884. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, kv.get_key().c_str(), kv.get_val<uint32_t>()); break;
  885. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, kv.get_key().c_str(), kv.get_val<int32_t>()); break;
  886. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, kv.get_key().c_str(), kv.get_val<float>()); break;
  887. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, kv.get_key().c_str(), kv.get_val<uint64_t>()); break;
  888. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, kv.get_key().c_str(), kv.get_val<int64_t>()); break;
  889. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, kv.get_key().c_str(), kv.get_val<double>()); break;
  890. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, kv.get_key().c_str(), kv.get_val<bool>()); break;
  891. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, kv.get_key().c_str(), kv.get_val<std::string>().c_str()); break;
  892. case GGUF_TYPE_ARRAY:
  893. default: GGML_ABORT("invalid type");
  894. }
  895. continue;
  896. }
  897. const size_t ne = kv.get_ne();
  898. switch (kv.get_type()) {
  899. case GGUF_TYPE_UINT8:
  900. case GGUF_TYPE_INT8:
  901. case GGUF_TYPE_UINT16:
  902. case GGUF_TYPE_INT16:
  903. case GGUF_TYPE_UINT32:
  904. case GGUF_TYPE_INT32:
  905. case GGUF_TYPE_FLOAT32:
  906. case GGUF_TYPE_UINT64:
  907. case GGUF_TYPE_INT64:
  908. case GGUF_TYPE_FLOAT64:
  909. case GGUF_TYPE_BOOL: {
  910. gguf_set_arr_data(ctx, kv.get_key().c_str(), kv.get_type(), kv.data.data(), ne);
  911. } break;
  912. case GGUF_TYPE_STRING: {
  913. std::vector<const char *> tmp(ne);
  914. for (size_t j = 0; j < ne; ++j) {
  915. tmp[j] = kv.data_string[j].c_str();
  916. }
  917. gguf_set_arr_str(ctx, kv.get_key().c_str(), tmp.data(), ne);
  918. } break;
  919. case GGUF_TYPE_ARRAY:
  920. default: GGML_ABORT("invalid type");
  921. }
  922. }
  923. }
  924. void gguf_add_tensor(
  925. struct gguf_context * ctx,
  926. const struct ggml_tensor * tensor) {
  927. GGML_ASSERT(tensor);
  928. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  929. GGML_ABORT("duplicate tensor name: %s", tensor->name);
  930. }
  931. struct gguf_tensor_info ti;
  932. ti.t = *tensor;
  933. ti.offset = ctx->info.empty() ? 0 :
  934. ctx->info.back().offset + GGML_PAD(ggml_nbytes(&ctx->info.back().t), ctx->alignment);
  935. ctx->info.push_back(ti);
  936. }
  937. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  938. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  939. if (tensor_id < 0) {
  940. GGML_ABORT("tensor not found: %s", name);
  941. }
  942. struct ggml_tensor * tensor = &ctx->info[tensor_id].t;
  943. const size_t type_size = ggml_type_size(type);
  944. const int64_t blck_size = ggml_blck_size(type);
  945. tensor->type = type;
  946. GGML_ASSERT(tensor->ne[0] % blck_size == 0 && "tensor row size not divisible by block size of new type");
  947. tensor->nb[0] = type_size;
  948. tensor->nb[1] = tensor->nb[0]*(tensor->ne[0]/blck_size);
  949. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  950. tensor->nb[i] = tensor->nb[i - 1]*tensor->ne[i - 1];
  951. }
  952. // update offsets
  953. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  954. for (int64_t i = tensor_id + 1; i < n_tensors; ++i) {
  955. ctx->info[i].offset = ctx->info[i - 1].offset + GGML_PAD(ggml_nbytes(&ctx->info[i - 1].t), ctx->alignment);
  956. }
  957. }
  958. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data) {
  959. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  960. if (tensor_id < 0) {
  961. GGML_ABORT("tensor not found: %s", name);
  962. }
  963. ctx->info[tensor_id].t.data = (void *)(uintptr_t)data; // double cast suppresses warning about casting away const
  964. }
  965. struct gguf_writer {
  966. std::vector<int8_t> & buf;
  967. gguf_writer(std::vector<int8_t> & buf) : buf(buf) {}
  968. template <typename T>
  969. void write(const T & val) const {
  970. for (size_t i = 0; i < sizeof(val); ++i) {
  971. buf.push_back(reinterpret_cast<const int8_t *>(&val)[i]);
  972. }
  973. }
  974. void write(const std::vector<int8_t> & val) const {
  975. buf.insert(buf.end(), val.begin(), val.end());
  976. }
  977. void write(const bool & val) const {
  978. const int8_t val8 = val ? 1 : 0;
  979. write(val8);
  980. }
  981. void write(const std::string & val) const {
  982. {
  983. const uint64_t n = val.length();
  984. write(n);
  985. }
  986. for (size_t i = 0; i < val.length(); ++i) {
  987. buf.push_back(reinterpret_cast<const int8_t *>(val.data())[i]);
  988. }
  989. }
  990. void write(const char * val) const {
  991. write(std::string(val));
  992. }
  993. void write(const enum ggml_type & val) const {
  994. write(int32_t(val));
  995. }
  996. void write(const enum gguf_type & val) const {
  997. write(int32_t(val));
  998. }
  999. void write(const struct gguf_kv & kv) const {
  1000. const uint64_t ne = kv.get_ne();
  1001. write(kv.get_key());
  1002. if (kv.is_array) {
  1003. write(GGUF_TYPE_ARRAY);
  1004. write(kv.get_type());
  1005. write(ne);
  1006. } else {
  1007. write(kv.get_type());
  1008. }
  1009. switch (kv.get_type()) {
  1010. case GGUF_TYPE_UINT8:
  1011. case GGUF_TYPE_INT8:
  1012. case GGUF_TYPE_UINT16:
  1013. case GGUF_TYPE_INT16:
  1014. case GGUF_TYPE_UINT32:
  1015. case GGUF_TYPE_INT32:
  1016. case GGUF_TYPE_FLOAT32:
  1017. case GGUF_TYPE_UINT64:
  1018. case GGUF_TYPE_INT64:
  1019. case GGUF_TYPE_FLOAT64: {
  1020. write(kv.data);
  1021. } break;
  1022. case GGUF_TYPE_BOOL: {
  1023. for (size_t i = 0; i < ne; ++i) {
  1024. write(kv.get_val<bool>(i));
  1025. }
  1026. } break;
  1027. case GGUF_TYPE_STRING: {
  1028. for (size_t i = 0; i < ne; ++i) {
  1029. write(kv.get_val<std::string>(i));
  1030. }
  1031. } break;
  1032. case GGUF_TYPE_ARRAY:
  1033. default: GGML_ABORT("invalid type");
  1034. }
  1035. }
  1036. void write_tensor_meta(const struct gguf_tensor_info & info) const {
  1037. write(info.t.name);
  1038. const uint32_t n_dims = ggml_n_dims(&info.t);
  1039. write(n_dims);
  1040. for (uint32_t j = 0; j < n_dims; ++j) {
  1041. write(info.t.ne[j]);
  1042. }
  1043. write(info.t.type);
  1044. write(info.offset);
  1045. }
  1046. void pad(const size_t alignment) const {
  1047. while (buf.size() % alignment != 0) {
  1048. const int8_t zero = 0;
  1049. write(zero);
  1050. }
  1051. }
  1052. void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) const {
  1053. GGML_ASSERT(buf.size() - offset_data == info.offset);
  1054. GGML_ASSERT(ggml_is_contiguous(&info.t));
  1055. const size_t offset = buf.size();
  1056. const size_t nbytes = ggml_nbytes(&info.t);
  1057. buf.resize(offset + nbytes);
  1058. if (info.t.buffer) {
  1059. ggml_backend_tensor_get(&info.t, buf.data() + offset, 0, nbytes);
  1060. } else {
  1061. GGML_ASSERT(info.t.data);
  1062. memcpy(buf.data() + offset, info.t.data, nbytes);
  1063. }
  1064. pad(alignment);
  1065. }
  1066. };
  1067. void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta) {
  1068. const struct gguf_writer gw(buf);
  1069. const int64_t n_kv = gguf_get_n_kv(ctx);
  1070. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  1071. // write header
  1072. gw.write(GGUF_MAGIC[0]);
  1073. gw.write(GGUF_MAGIC[1]);
  1074. gw.write(GGUF_MAGIC[2]);
  1075. gw.write(GGUF_MAGIC[3]);
  1076. gw.write(ctx->version);
  1077. gw.write(n_tensors);
  1078. gw.write(n_kv);
  1079. // write key-value pairs
  1080. for (int64_t i = 0; i < n_kv; ++i) {
  1081. gw.write(ctx->kv[i]);
  1082. }
  1083. // write tensor info
  1084. for (int64_t i = 0; i < n_tensors; ++i) {
  1085. gw.write_tensor_meta(ctx->info[i]);
  1086. }
  1087. // we require the data section to be aligned
  1088. gw.pad(ctx->alignment);
  1089. if (only_meta) {
  1090. return;
  1091. }
  1092. const size_t offset_data = gw.buf.size();
  1093. // write tensor data
  1094. for (int64_t i = 0; i < n_tensors; ++i) {
  1095. gw.write_tensor_data(ctx->info[i], offset_data, ctx->alignment);
  1096. }
  1097. }
  1098. bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  1099. FILE * file = ggml_fopen(fname, "wb");
  1100. if (!file) {
  1101. fprintf(stderr, "%s: failed to open file '%s' for writing GGUF data\n", __func__, fname);
  1102. return false;
  1103. }
  1104. std::vector<int8_t> buf;
  1105. gguf_write_to_buf(ctx, buf, only_meta);
  1106. const bool ok = fwrite(buf.data(), 1, buf.size(), file) == buf.size();
  1107. fclose(file);
  1108. return ok;
  1109. }
  1110. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  1111. // only return size
  1112. std::vector<int8_t> buf;
  1113. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1114. return buf.size();
  1115. }
  1116. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  1117. std::vector<int8_t> buf;
  1118. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1119. memcpy(data, buf.data(), buf.size());
  1120. }