gguf.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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. // read the binary blob with the tensor data
  564. ok = ok && gr.read(data->data, ctx->size);
  565. if (!ok) {
  566. fprintf(stderr, "%s: failed to read tensor data binary blob\n", __func__);
  567. ggml_free(ctx_data);
  568. *params.ctx = nullptr;
  569. gguf_free(ctx);
  570. return nullptr;
  571. }
  572. ctx->data = data->data;
  573. }
  574. ggml_set_no_alloc(ctx_data, true);
  575. // create the tensors
  576. for (size_t i = 0; i < ctx->info.size(); ++i) {
  577. const struct gguf_tensor_info & info = ctx->info[i];
  578. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
  579. ok = ok && cur != nullptr;
  580. if (!ok) {
  581. break;
  582. }
  583. ggml_set_name(cur, info.t.name);
  584. // point the data member to the appropriate location in the binary blob using the tensor info
  585. if (!params.no_alloc) {
  586. cur->data = (char *) data->data + info.offset;
  587. }
  588. }
  589. if (!ok) {
  590. fprintf(stderr, "%s: failed to create tensors\n", __func__);
  591. ggml_free(ctx_data);
  592. *params.ctx = nullptr;
  593. gguf_free(ctx);
  594. return nullptr;
  595. }
  596. ggml_set_no_alloc(ctx_data, params.no_alloc);
  597. }
  598. return ctx;
  599. }
  600. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  601. FILE * file = ggml_fopen(fname, "rb");
  602. if (!file) {
  603. fprintf(stderr, "%s: failed to open GGUF file '%s'\n", __func__, fname);
  604. return nullptr;
  605. }
  606. struct gguf_context * result = gguf_init_from_file_impl(file, params);
  607. fclose(file);
  608. return result;
  609. }
  610. void gguf_free(struct gguf_context * ctx) {
  611. if (ctx == nullptr) {
  612. return;
  613. }
  614. delete ctx;
  615. }
  616. const char * gguf_type_name(enum gguf_type type) {
  617. auto it = GGUF_TYPE_NAME.find(type);
  618. return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
  619. }
  620. uint32_t gguf_get_version(const struct gguf_context * ctx) {
  621. return ctx->version;
  622. }
  623. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  624. return ctx->alignment;
  625. }
  626. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  627. return ctx->offset;
  628. }
  629. int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
  630. return ctx->kv.size();
  631. }
  632. int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
  633. // return -1 if key not found
  634. int64_t keyfound = -1;
  635. const int64_t n_kv = gguf_get_n_kv(ctx);
  636. for (int64_t i = 0; i < n_kv; ++i) {
  637. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  638. keyfound = i;
  639. break;
  640. }
  641. }
  642. return keyfound;
  643. }
  644. const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
  645. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  646. return ctx->kv[key_id].get_key().c_str();
  647. }
  648. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
  649. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  650. return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
  651. }
  652. enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id) {
  653. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  654. GGML_ASSERT(ctx->kv[key_id].is_array);
  655. return ctx->kv[key_id].get_type();
  656. }
  657. const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id) {
  658. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  659. GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
  660. return ctx->kv[key_id].data.data();
  661. }
  662. const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
  663. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  664. GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
  665. return ctx->kv[key_id].data_string[i].c_str();
  666. }
  667. size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
  668. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  669. if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
  670. return ctx->kv[key_id].data_string.size();
  671. }
  672. const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
  673. GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
  674. return ctx->kv[key_id].data.size() / type_size;
  675. }
  676. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
  677. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  678. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  679. return ctx->kv[key_id].get_val<uint8_t>();
  680. }
  681. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
  682. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  683. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  684. return ctx->kv[key_id].get_val<int8_t>();
  685. }
  686. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
  687. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  688. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  689. return ctx->kv[key_id].get_val<uint16_t>();
  690. }
  691. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
  692. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  693. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  694. return ctx->kv[key_id].get_val<int16_t>();
  695. }
  696. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
  697. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  698. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  699. return ctx->kv[key_id].get_val<uint32_t>();
  700. }
  701. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
  702. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  703. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  704. return ctx->kv[key_id].get_val<int32_t>();
  705. }
  706. float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
  707. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  708. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  709. return ctx->kv[key_id].get_val<float>();
  710. }
  711. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
  712. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  713. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  714. return ctx->kv[key_id].get_val<uint64_t>();
  715. }
  716. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
  717. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  718. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  719. return ctx->kv[key_id].get_val<int64_t>();
  720. }
  721. double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
  722. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  723. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  724. return ctx->kv[key_id].get_val<double>();
  725. }
  726. bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
  727. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  728. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  729. return ctx->kv[key_id].get_val<bool>();
  730. }
  731. const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
  732. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  733. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  734. return ctx->kv[key_id].get_val<std::string>().c_str();
  735. }
  736. const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
  737. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  738. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  739. GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
  740. return ctx->kv[key_id].data.data();
  741. }
  742. int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
  743. return ctx->info.size();
  744. }
  745. int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  746. // return -1 if tensor not found
  747. int64_t tensor_id = -1;
  748. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  749. for (int64_t i = 0; i < n_tensors; ++i) {
  750. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  751. tensor_id = i;
  752. break;
  753. }
  754. }
  755. return tensor_id;
  756. }
  757. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
  758. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  759. return ctx->info[tensor_id].offset;
  760. }
  761. const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
  762. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  763. return ctx->info[tensor_id].t.name;
  764. }
  765. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
  766. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  767. return ctx->info[tensor_id].t.type;
  768. }
  769. size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
  770. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  771. return ggml_nbytes(&ctx->info[tensor_id].t);
  772. }
  773. int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
  774. const int64_t key_id = gguf_find_key(ctx, key);
  775. if (key_id >= 0) {
  776. ctx->kv.erase(ctx->kv.begin() + key_id);
  777. }
  778. return key_id;
  779. }
  780. template<typename T>
  781. static void gguf_check_reserved_keys(const std::string & key, const T val) {
  782. if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
  783. if constexpr (std::is_same<T, uint32_t>::value) {
  784. GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
  785. } else {
  786. GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
  787. }
  788. }
  789. }
  790. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
  791. gguf_check_reserved_keys(key, val);
  792. gguf_remove_key(ctx, key);
  793. ctx->kv.emplace_back(key, val);
  794. }
  795. void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
  796. gguf_check_reserved_keys(key, val);
  797. gguf_remove_key(ctx, key);
  798. ctx->kv.emplace_back(key, val);
  799. }
  800. void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
  801. gguf_check_reserved_keys(key, val);
  802. gguf_remove_key(ctx, key);
  803. ctx->kv.emplace_back(key, val);
  804. }
  805. void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
  806. gguf_check_reserved_keys(key, val);
  807. gguf_remove_key(ctx, key);
  808. ctx->kv.emplace_back(key, val);
  809. }
  810. void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
  811. gguf_check_reserved_keys(key, val);
  812. gguf_remove_key(ctx, key);
  813. ctx->kv.emplace_back(key, val);
  814. }
  815. void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  816. gguf_check_reserved_keys(key, val);
  817. gguf_remove_key(ctx, key);
  818. ctx->kv.emplace_back(key, val);
  819. }
  820. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  821. gguf_check_reserved_keys(key, val);
  822. gguf_remove_key(ctx, key);
  823. ctx->kv.emplace_back(key, val);
  824. }
  825. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  826. gguf_check_reserved_keys(key, val);
  827. gguf_remove_key(ctx, key);
  828. ctx->kv.emplace_back(key, val);
  829. }
  830. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  831. gguf_check_reserved_keys(key, val);
  832. gguf_remove_key(ctx, key);
  833. ctx->kv.emplace_back(key, val);
  834. }
  835. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  836. gguf_check_reserved_keys(key, val);
  837. gguf_remove_key(ctx, key);
  838. ctx->kv.emplace_back(key, val);
  839. }
  840. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  841. gguf_check_reserved_keys(key, val);
  842. gguf_remove_key(ctx, key);
  843. ctx->kv.emplace_back(key, val);
  844. }
  845. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  846. gguf_check_reserved_keys(key, val);
  847. gguf_remove_key(ctx, key);
  848. ctx->kv.emplace_back(key, std::string(val));
  849. }
  850. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n) {
  851. gguf_check_reserved_keys(key, data);
  852. gguf_remove_key(ctx, key);
  853. const size_t nbytes = n*gguf_type_size(type);
  854. std::vector<int8_t> tmp(nbytes);
  855. if (!tmp.empty()) {
  856. memcpy(tmp.data(), data, nbytes);
  857. }
  858. ctx->kv.emplace_back(key, tmp);
  859. ctx->kv.back().cast(type);
  860. }
  861. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, size_t n) {
  862. gguf_check_reserved_keys(key, data);
  863. gguf_remove_key(ctx, key);
  864. std::vector<std::string> tmp(n);
  865. for (size_t i = 0; i < n; ++i) {
  866. tmp[i] = data[i];
  867. }
  868. ctx->kv.emplace_back(key, tmp);
  869. }
  870. // set or add KV pairs from another context
  871. void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src) {
  872. const int64_t n_kv = gguf_get_n_kv(src);
  873. for (int64_t i = 0; i < n_kv; ++i) {
  874. const struct gguf_kv & kv = src->kv[i];
  875. if (!kv.is_array) {
  876. switch (kv.get_type()) {
  877. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, kv.get_key().c_str(), kv.get_val<uint8_t>()); break;
  878. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, kv.get_key().c_str(), kv.get_val<int8_t>()); break;
  879. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, kv.get_key().c_str(), kv.get_val<uint16_t>()); break;
  880. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, kv.get_key().c_str(), kv.get_val<int16_t>()); break;
  881. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, kv.get_key().c_str(), kv.get_val<uint32_t>()); break;
  882. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, kv.get_key().c_str(), kv.get_val<int32_t>()); break;
  883. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, kv.get_key().c_str(), kv.get_val<float>()); break;
  884. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, kv.get_key().c_str(), kv.get_val<uint64_t>()); break;
  885. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, kv.get_key().c_str(), kv.get_val<int64_t>()); break;
  886. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, kv.get_key().c_str(), kv.get_val<double>()); break;
  887. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, kv.get_key().c_str(), kv.get_val<bool>()); break;
  888. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, kv.get_key().c_str(), kv.get_val<std::string>().c_str()); break;
  889. case GGUF_TYPE_ARRAY:
  890. default: GGML_ABORT("invalid type");
  891. }
  892. continue;
  893. }
  894. const size_t ne = kv.get_ne();
  895. switch (kv.get_type()) {
  896. case GGUF_TYPE_UINT8:
  897. case GGUF_TYPE_INT8:
  898. case GGUF_TYPE_UINT16:
  899. case GGUF_TYPE_INT16:
  900. case GGUF_TYPE_UINT32:
  901. case GGUF_TYPE_INT32:
  902. case GGUF_TYPE_FLOAT32:
  903. case GGUF_TYPE_UINT64:
  904. case GGUF_TYPE_INT64:
  905. case GGUF_TYPE_FLOAT64:
  906. case GGUF_TYPE_BOOL: {
  907. gguf_set_arr_data(ctx, kv.get_key().c_str(), kv.get_type(), kv.data.data(), ne);
  908. } break;
  909. case GGUF_TYPE_STRING: {
  910. std::vector<const char *> tmp(ne);
  911. for (size_t j = 0; j < ne; ++j) {
  912. tmp[j] = kv.data_string[j].c_str();
  913. }
  914. gguf_set_arr_str(ctx, kv.get_key().c_str(), tmp.data(), ne);
  915. } break;
  916. case GGUF_TYPE_ARRAY:
  917. default: GGML_ABORT("invalid type");
  918. }
  919. }
  920. }
  921. void gguf_add_tensor(
  922. struct gguf_context * ctx,
  923. const struct ggml_tensor * tensor) {
  924. GGML_ASSERT(tensor);
  925. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  926. GGML_ABORT("duplicate tensor name: %s", tensor->name);
  927. }
  928. struct gguf_tensor_info ti;
  929. ti.t = *tensor;
  930. ti.offset = ctx->info.empty() ? 0 :
  931. ctx->info.back().offset + GGML_PAD(ggml_nbytes(&ctx->info.back().t), ctx->alignment);
  932. ctx->info.push_back(ti);
  933. }
  934. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  935. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  936. if (tensor_id < 0) {
  937. GGML_ABORT("tensor not found: %s", name);
  938. }
  939. struct ggml_tensor * tensor = &ctx->info[tensor_id].t;
  940. const size_t type_size = ggml_type_size(type);
  941. const int64_t blck_size = ggml_blck_size(type);
  942. tensor->type = type;
  943. GGML_ASSERT(tensor->ne[0] % blck_size == 0 && "tensor row size not divisible by block size of new type");
  944. tensor->nb[0] = type_size;
  945. tensor->nb[1] = tensor->nb[0]*(tensor->ne[0]/blck_size);
  946. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  947. tensor->nb[i] = tensor->nb[i - 1]*tensor->ne[i - 1];
  948. }
  949. // update offsets
  950. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  951. for (int64_t i = tensor_id + 1; i < n_tensors; ++i) {
  952. ctx->info[i].offset = ctx->info[i - 1].offset + GGML_PAD(ggml_nbytes(&ctx->info[i - 1].t), ctx->alignment);
  953. }
  954. }
  955. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data) {
  956. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  957. if (tensor_id < 0) {
  958. GGML_ABORT("tensor not found: %s", name);
  959. }
  960. ctx->info[tensor_id].t.data = (void *)(uintptr_t)data; // double cast suppresses warning about casting away const
  961. }
  962. struct gguf_writer {
  963. std::vector<int8_t> & buf;
  964. gguf_writer(std::vector<int8_t> & buf) : buf(buf) {}
  965. template <typename T>
  966. void write(const T & val) const {
  967. for (size_t i = 0; i < sizeof(val); ++i) {
  968. buf.push_back(reinterpret_cast<const int8_t *>(&val)[i]);
  969. }
  970. }
  971. void write(const std::vector<int8_t> & val) const {
  972. buf.insert(buf.end(), val.begin(), val.end());
  973. }
  974. void write(const bool & val) const {
  975. const int8_t val8 = val ? 1 : 0;
  976. write(val8);
  977. }
  978. void write(const std::string & val) const {
  979. {
  980. const uint64_t n = val.length();
  981. write(n);
  982. }
  983. for (size_t i = 0; i < val.length(); ++i) {
  984. buf.push_back(reinterpret_cast<const int8_t *>(val.data())[i]);
  985. }
  986. }
  987. void write(const char * val) const {
  988. write(std::string(val));
  989. }
  990. void write(const enum ggml_type & val) const {
  991. write(int32_t(val));
  992. }
  993. void write(const enum gguf_type & val) const {
  994. write(int32_t(val));
  995. }
  996. void write(const struct gguf_kv & kv) const {
  997. const uint64_t ne = kv.get_ne();
  998. write(kv.get_key());
  999. if (kv.is_array) {
  1000. write(GGUF_TYPE_ARRAY);
  1001. write(kv.get_type());
  1002. write(ne);
  1003. } else {
  1004. write(kv.get_type());
  1005. }
  1006. switch (kv.get_type()) {
  1007. case GGUF_TYPE_UINT8:
  1008. case GGUF_TYPE_INT8:
  1009. case GGUF_TYPE_UINT16:
  1010. case GGUF_TYPE_INT16:
  1011. case GGUF_TYPE_UINT32:
  1012. case GGUF_TYPE_INT32:
  1013. case GGUF_TYPE_FLOAT32:
  1014. case GGUF_TYPE_UINT64:
  1015. case GGUF_TYPE_INT64:
  1016. case GGUF_TYPE_FLOAT64: {
  1017. write(kv.data);
  1018. } break;
  1019. case GGUF_TYPE_BOOL: {
  1020. for (size_t i = 0; i < ne; ++i) {
  1021. write(kv.get_val<bool>(i));
  1022. }
  1023. } break;
  1024. case GGUF_TYPE_STRING: {
  1025. for (size_t i = 0; i < ne; ++i) {
  1026. write(kv.get_val<std::string>(i));
  1027. }
  1028. } break;
  1029. case GGUF_TYPE_ARRAY:
  1030. default: GGML_ABORT("invalid type");
  1031. }
  1032. }
  1033. void write_tensor_meta(const struct gguf_tensor_info & info) const {
  1034. write(info.t.name);
  1035. const uint32_t n_dims = ggml_n_dims(&info.t);
  1036. write(n_dims);
  1037. for (uint32_t j = 0; j < n_dims; ++j) {
  1038. write(info.t.ne[j]);
  1039. }
  1040. write(info.t.type);
  1041. write(info.offset);
  1042. }
  1043. void pad(const size_t alignment) const {
  1044. while (buf.size() % alignment != 0) {
  1045. const int8_t zero = 0;
  1046. write(zero);
  1047. }
  1048. }
  1049. void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) const {
  1050. GGML_ASSERT(buf.size() - offset_data == info.offset);
  1051. GGML_ASSERT(ggml_is_contiguous(&info.t));
  1052. const size_t offset = buf.size();
  1053. const size_t nbytes = ggml_nbytes(&info.t);
  1054. buf.resize(offset + nbytes);
  1055. if (info.t.buffer) {
  1056. ggml_backend_tensor_get(&info.t, buf.data() + offset, 0, nbytes);
  1057. } else {
  1058. GGML_ASSERT(info.t.data);
  1059. memcpy(buf.data() + offset, info.t.data, nbytes);
  1060. }
  1061. pad(alignment);
  1062. }
  1063. };
  1064. void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta) {
  1065. const struct gguf_writer gw(buf);
  1066. const int64_t n_kv = gguf_get_n_kv(ctx);
  1067. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  1068. // write header
  1069. gw.write(GGUF_MAGIC[0]);
  1070. gw.write(GGUF_MAGIC[1]);
  1071. gw.write(GGUF_MAGIC[2]);
  1072. gw.write(GGUF_MAGIC[3]);
  1073. gw.write(ctx->version);
  1074. gw.write(n_tensors);
  1075. gw.write(n_kv);
  1076. // write key-value pairs
  1077. for (int64_t i = 0; i < n_kv; ++i) {
  1078. gw.write(ctx->kv[i]);
  1079. }
  1080. // write tensor info
  1081. for (int64_t i = 0; i < n_tensors; ++i) {
  1082. gw.write_tensor_meta(ctx->info[i]);
  1083. }
  1084. // we require the data section to be aligned
  1085. gw.pad(ctx->alignment);
  1086. if (only_meta) {
  1087. return;
  1088. }
  1089. const size_t offset_data = gw.buf.size();
  1090. // write tensor data
  1091. for (int64_t i = 0; i < n_tensors; ++i) {
  1092. gw.write_tensor_data(ctx->info[i], offset_data, ctx->alignment);
  1093. }
  1094. }
  1095. bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  1096. FILE * file = ggml_fopen(fname, "wb");
  1097. if (!file) {
  1098. fprintf(stderr, "%s: failed to open file '%s' for writing GGUF data\n", __func__, fname);
  1099. return false;
  1100. }
  1101. std::vector<int8_t> buf;
  1102. gguf_write_to_buf(ctx, buf, only_meta);
  1103. const bool ok = fwrite(buf.data(), 1, buf.size(), file) == buf.size();
  1104. fclose(file);
  1105. return ok;
  1106. }
  1107. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  1108. // only return size
  1109. std::vector<int8_t> buf;
  1110. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1111. return buf.size();
  1112. }
  1113. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  1114. std::vector<int8_t> buf;
  1115. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1116. memcpy(data, buf.data(), buf.size());
  1117. }