gguf.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  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 = 0;
  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. GGML_LOG_ERROR("%s: encountered length_error while reading value for key '%s'\n", __func__, key.c_str());
  258. return false;
  259. } catch (std::bad_alloc &) {
  260. GGML_LOG_ERROR("%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. GGML_LOG_ERROR("%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. char c0 = isprint(magic[0]) ? magic[0] : '?';
  289. char c1 = isprint(magic[1]) ? magic[1] : '?';
  290. char c2 = isprint(magic[2]) ? magic[2] : '?';
  291. char c3 = isprint(magic[3]) ? magic[3] : '?';
  292. GGML_LOG_ERROR("%s: invalid magic characters: '%c%c%c%c', expected 'GGUF'\n", __func__, c0, c1, c2, c3);
  293. gguf_free(ctx);
  294. return nullptr;
  295. }
  296. }
  297. }
  298. // header
  299. int64_t n_kv = 0;
  300. int64_t n_tensors = 0;
  301. if (ok && gr.read(ctx->version)) {
  302. if (ok && ctx->version == 0) {
  303. GGML_LOG_ERROR("%s: bad GGUF version: %" PRIu32 "\n", __func__, ctx->version);
  304. ok = false;
  305. }
  306. /*
  307. * bit layout is different when reading non-native endian models.
  308. * assuming that the GGUF version is 3, the non-native endian model
  309. * would read it as 0x30000000. we can use the AND operation against
  310. * the last 4 hexadecimal digits to check if the model is the same
  311. * endianness as the host system.
  312. */
  313. if (ok && (ctx->version & 0x0000FFFF) == 0x00000000) {
  314. GGML_LOG_ERROR("%s: failed to load model: this GGUF file version %" PRIu32 " is extremely large, is there a mismatch between the host and model endianness?\n", __func__, ctx->version);
  315. ok = false;
  316. }
  317. if (ok && ctx->version == 1) {
  318. GGML_LOG_ERROR("%s: GGUFv1 is no longer supported, please use a more up-to-date version\n", __func__);
  319. ok = false;
  320. }
  321. if (ok && ctx->version > GGUF_VERSION) {
  322. GGML_LOG_ERROR("%s: this GGUF file is version %" PRIu32 " but this software only supports up to version %d\n",
  323. __func__, ctx->version, GGUF_VERSION);
  324. ok = false;
  325. }
  326. } else {
  327. ok = false;
  328. }
  329. if (ok && gr.read(n_tensors)) {
  330. static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
  331. if (n_tensors < 0 || n_tensors > int64_t(SIZE_MAX/sizeof(gguf_tensor_info))) {
  332. GGML_LOG_ERROR("%s: number of tensors is %" PRIi64 " but must be in [0, %zu]\n",
  333. __func__, n_tensors, SIZE_MAX/sizeof(gguf_tensor_info));
  334. ok = false;
  335. }
  336. } else {
  337. ok = false;
  338. }
  339. if (ok && gr.read(n_kv)) {
  340. static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
  341. if (n_kv < 0 || n_kv > int64_t(SIZE_MAX/sizeof(gguf_kv))) {
  342. GGML_LOG_ERROR("%s: number of key value pairs is %" PRIi64 " but must be in [0, %zu]\n",
  343. __func__, n_kv, SIZE_MAX/sizeof(gguf_kv));
  344. ok = false;
  345. }
  346. } else {
  347. ok = false;
  348. }
  349. if (!ok) {
  350. GGML_LOG_ERROR("%s: failed to read header\n", __func__);
  351. gguf_free(ctx);
  352. return nullptr;
  353. }
  354. // KV pairs
  355. {
  356. for (int64_t i = 0; ok && i < n_kv; ++i) {
  357. std::string key;
  358. gguf_type type = gguf_type(-1);
  359. bool is_array = false;
  360. uint64_t n = 1;
  361. try {
  362. ok = ok && gr.read(key);
  363. } catch (std::length_error &) {
  364. GGML_LOG_ERROR("%s: encountered length_error while reading key %" PRIi64 "\n", __func__, i);
  365. ok = false;
  366. } catch (std::bad_alloc &) {
  367. GGML_LOG_ERROR("%s: encountered bad_alloc error while reading key %" PRIi64 "\n", __func__, i);
  368. ok = false;
  369. }
  370. for (size_t j = 0; ok && j < ctx->kv.size(); ++j) {
  371. if (key == ctx->kv[j].key) {
  372. GGML_LOG_ERROR("%s: duplicate key '%s' for tensors %zu and %" PRIi64 " \n", __func__, key.c_str(), j, i);
  373. ok = false;
  374. }
  375. }
  376. if (!ok) {
  377. break;
  378. }
  379. ok = ok && gr.read(type);
  380. if (type == GGUF_TYPE_ARRAY) {
  381. is_array = true;
  382. ok = ok && gr.read(type);
  383. ok = ok && gr.read(n);
  384. }
  385. if (!ok) {
  386. break;
  387. }
  388. switch (type) {
  389. case GGUF_TYPE_UINT8: ok = ok && gguf_read_emplace_helper<uint8_t> (gr, ctx->kv, key, is_array, n); break;
  390. case GGUF_TYPE_INT8: ok = ok && gguf_read_emplace_helper<int8_t> (gr, ctx->kv, key, is_array, n); break;
  391. case GGUF_TYPE_UINT16: ok = ok && gguf_read_emplace_helper<uint16_t> (gr, ctx->kv, key, is_array, n); break;
  392. case GGUF_TYPE_INT16: ok = ok && gguf_read_emplace_helper<int16_t> (gr, ctx->kv, key, is_array, n); break;
  393. case GGUF_TYPE_UINT32: ok = ok && gguf_read_emplace_helper<uint32_t> (gr, ctx->kv, key, is_array, n); break;
  394. case GGUF_TYPE_INT32: ok = ok && gguf_read_emplace_helper<int32_t> (gr, ctx->kv, key, is_array, n); break;
  395. case GGUF_TYPE_FLOAT32: ok = ok && gguf_read_emplace_helper<float> (gr, ctx->kv, key, is_array, n); break;
  396. case GGUF_TYPE_BOOL: ok = ok && gguf_read_emplace_helper<bool> (gr, ctx->kv, key, is_array, n); break;
  397. case GGUF_TYPE_STRING: ok = ok && gguf_read_emplace_helper<std::string>(gr, ctx->kv, key, is_array, n); break;
  398. case GGUF_TYPE_UINT64: ok = ok && gguf_read_emplace_helper<uint64_t> (gr, ctx->kv, key, is_array, n); break;
  399. case GGUF_TYPE_INT64: ok = ok && gguf_read_emplace_helper<int64_t> (gr, ctx->kv, key, is_array, n); break;
  400. case GGUF_TYPE_FLOAT64: ok = ok && gguf_read_emplace_helper<double> (gr, ctx->kv, key, is_array, n); break;
  401. case GGUF_TYPE_ARRAY:
  402. default:
  403. {
  404. GGML_LOG_ERROR("%s: key '%s' has invalid GGUF type %d\n", __func__, key.c_str(), type);
  405. ok = false;
  406. } break;
  407. }
  408. }
  409. if (!ok) {
  410. GGML_LOG_ERROR("%s: failed to read key-value pairs\n", __func__);
  411. gguf_free(ctx);
  412. return nullptr;
  413. }
  414. GGML_ASSERT(int64_t(ctx->kv.size()) == n_kv);
  415. const int alignment_idx = gguf_find_key(ctx, GGUF_KEY_GENERAL_ALIGNMENT);
  416. ctx->alignment = alignment_idx == -1 ? GGUF_DEFAULT_ALIGNMENT : gguf_get_val_u32(ctx, alignment_idx);
  417. if (ctx->alignment == 0 || (ctx->alignment & (ctx->alignment - 1)) != 0) {
  418. GGML_LOG_ERROR("%s: alignment %zu is not a power of 2\n", __func__, ctx->alignment);
  419. gguf_free(ctx);
  420. return nullptr;
  421. }
  422. }
  423. // read the tensor info
  424. for (int64_t i = 0; ok && i < n_tensors; ++i) {
  425. struct gguf_tensor_info info;
  426. // tensor name
  427. {
  428. std::string name;
  429. try {
  430. ok = ok && gr.read(name);
  431. } catch (std::length_error &) {
  432. GGML_LOG_ERROR("%s: encountered length_error while reading tensor name %" PRIi64 "\n", __func__, i);
  433. ok = false;
  434. } catch (std::bad_alloc &) {
  435. GGML_LOG_ERROR("%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
  436. ok = false;
  437. }
  438. if (name.length() >= GGML_MAX_NAME) {
  439. GGML_LOG_ERROR("%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
  440. ok = false;
  441. break;
  442. }
  443. ggml_set_name(&info.t, name.c_str());
  444. // make sure there are no duplicate tensor names
  445. for (int64_t j = 0; ok && j < i; ++j) {
  446. if (strcmp(info.t.name, ctx->info[j].t.name) == 0) {
  447. GGML_LOG_ERROR("%s: duplicate tensor name '%s' for tensors %" PRIi64 " and %" PRIi64 "\n", __func__, info.t.name, j, i);
  448. ok = false;
  449. break;
  450. }
  451. }
  452. }
  453. if (!ok) {
  454. break;
  455. }
  456. // tensor shape
  457. {
  458. uint32_t n_dims = 0;
  459. ok = ok && gr.read(n_dims);
  460. if (n_dims > GGML_MAX_DIMS) {
  461. GGML_LOG_ERROR("%s: tensor '%s' has invalid number of dimensions: %" PRIu32 " > %" PRIu32 "\n",
  462. __func__, info.t.name, n_dims, GGML_MAX_DIMS);
  463. ok = false;
  464. break;
  465. }
  466. for (uint32_t j = 0; ok && j < GGML_MAX_DIMS; ++j) {
  467. info.t.ne[j] = 1;
  468. if (j < n_dims) {
  469. ok = ok && gr.read(info.t.ne[j]);
  470. }
  471. // check that all ne are non-negative
  472. if (info.t.ne[j] < 0) {
  473. GGML_LOG_ERROR("%s: tensor '%s' dimension %" PRIu32 " has invalid number of elements: %" PRIi64 " < 0\n",
  474. __func__, info.t.name, j, info.t.ne[j]);
  475. ok = false;
  476. break;
  477. }
  478. }
  479. // check that the total number of elements is representable
  480. if (ok && ((INT64_MAX/info.t.ne[1] <= info.t.ne[0]) ||
  481. (INT64_MAX/info.t.ne[2] <= info.t.ne[0]*info.t.ne[1]) ||
  482. (INT64_MAX/info.t.ne[3] <= info.t.ne[0]*info.t.ne[1]*info.t.ne[2]))) {
  483. GGML_LOG_ERROR("%s: total number of elements in tensor '%s' with shape "
  484. "(%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") is >= %" PRIi64 "\n",
  485. __func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], INT64_MAX);
  486. ok = false;
  487. break;
  488. }
  489. }
  490. if (!ok) {
  491. break;
  492. }
  493. // tensor type
  494. {
  495. ok = ok && gr.read(info.t.type);
  496. // check that tensor type is within defined range
  497. if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
  498. GGML_LOG_ERROR("%s: tensor '%s' has invalid ggml type %d (%s)\n",
  499. __func__, info.t.name, info.t.type, ggml_type_name(info.t.type));
  500. ok = false;
  501. break;
  502. }
  503. const size_t type_size = ggml_type_size(info.t.type);
  504. const int64_t blck_size = ggml_blck_size(info.t.type);
  505. // check that row size is divisible by block size
  506. if (blck_size == 0 || info.t.ne[0] % blck_size != 0) {
  507. GGML_LOG_ERROR("%s: tensor '%s' of type %d (%s) has %" PRId64 " elements per row, "
  508. "not a multiple of block size (%" PRId64 ")\n",
  509. __func__, info.t.name, (int) info.t.type, ggml_type_name(info.t.type), info.t.ne[0], blck_size);
  510. ok = false;
  511. break;
  512. }
  513. // calculate byte offsets given the tensor shape and type
  514. info.t.nb[0] = type_size;
  515. info.t.nb[1] = info.t.nb[0]*(info.t.ne[0]/blck_size);
  516. for (int j = 2; j < GGML_MAX_DIMS; ++j) {
  517. info.t.nb[j] = info.t.nb[j - 1]*info.t.ne[j - 1];
  518. }
  519. }
  520. if (!ok) {
  521. break;
  522. }
  523. // tensor data offset within buffer
  524. ok = ok && gr.read(info.offset);
  525. ctx->info.push_back(info);
  526. }
  527. if (!ok) {
  528. GGML_LOG_ERROR("%s: failed to read tensor info\n", __func__);
  529. gguf_free(ctx);
  530. return nullptr;
  531. }
  532. GGML_ASSERT(int64_t(ctx->info.size()) == n_tensors);
  533. // we require the data section to be aligned, so take into account any padding
  534. if (fseek(file, GGML_PAD(ftell(file), ctx->alignment), SEEK_SET) != 0) {
  535. GGML_LOG_ERROR("%s: failed to seek to beginning of data section\n", __func__);
  536. gguf_free(ctx);
  537. return nullptr;
  538. }
  539. // store the current file offset - this is where the data section starts
  540. ctx->offset = ftell(file);
  541. // compute the total size of the data section, taking into account the alignment
  542. {
  543. ctx->size = 0;
  544. for (size_t i = 0; i < ctx->info.size(); ++i) {
  545. const gguf_tensor_info & ti = ctx->info[i];
  546. if (ti.offset != ctx->size) {
  547. GGML_LOG_ERROR("%s: tensor '%s' has offset %" PRIu64 ", expected %zu\n",
  548. __func__, ti.t.name, ti.offset, ctx->size);
  549. GGML_LOG_ERROR("%s: failed to read tensor data\n", __func__);
  550. gguf_free(ctx);
  551. return nullptr;
  552. }
  553. size_t padded_size = GGML_PAD(ggml_nbytes(&ti.t), ctx->alignment);
  554. if (SIZE_MAX - ctx->size < padded_size) {
  555. GGML_LOG_ERROR("%s: tensor '%s' size overflow, cannot accumulate size %zu + %zu\n",
  556. __func__, ti.t.name, ctx->size, padded_size);
  557. gguf_free(ctx);
  558. return nullptr;
  559. }
  560. ctx->size += padded_size;
  561. }
  562. }
  563. // load the tensor data only if requested
  564. if (params.ctx != nullptr) {
  565. // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
  566. // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
  567. // the ggml_tensor structs to the appropriate locations in the binary blob
  568. // compute the exact size needed for the new ggml_context
  569. const size_t mem_size =
  570. params.no_alloc ?
  571. (n_tensors )*ggml_tensor_overhead() :
  572. (n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
  573. struct ggml_init_params pdata = {
  574. /*mem_size =*/ mem_size,
  575. /*mem_buffer =*/ nullptr,
  576. /*no_alloc =*/ params.no_alloc,
  577. };
  578. *params.ctx = ggml_init(pdata);
  579. if (*params.ctx == nullptr) {
  580. GGML_LOG_ERROR("%s: failed to initialize ggml context for storing tensors\n", __func__);
  581. gguf_free(ctx);
  582. return nullptr;
  583. }
  584. struct ggml_context * ctx_data = *params.ctx;
  585. struct ggml_tensor * data = nullptr;
  586. if (!params.no_alloc) {
  587. data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
  588. ok = ok && data != nullptr;
  589. if (ok) {
  590. ggml_set_name(data, "GGUF tensor data binary blob");
  591. }
  592. // read the binary blob with the tensor data
  593. ok = ok && gr.read(data->data, ctx->size);
  594. if (!ok) {
  595. GGML_LOG_ERROR("%s: failed to read tensor data binary blob\n", __func__);
  596. ggml_free(ctx_data);
  597. *params.ctx = nullptr;
  598. gguf_free(ctx);
  599. return nullptr;
  600. }
  601. ctx->data = data->data;
  602. }
  603. ggml_set_no_alloc(ctx_data, true);
  604. // create the tensors
  605. for (size_t i = 0; i < ctx->info.size(); ++i) {
  606. const struct gguf_tensor_info & info = ctx->info[i];
  607. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
  608. ok = ok && cur != nullptr;
  609. if (!ok) {
  610. break;
  611. }
  612. ggml_set_name(cur, info.t.name);
  613. // point the data member to the appropriate location in the binary blob using the tensor info
  614. if (!params.no_alloc) {
  615. cur->data = (char *) data->data + info.offset;
  616. }
  617. }
  618. if (!ok) {
  619. GGML_LOG_ERROR("%s: failed to create tensors\n", __func__);
  620. ggml_free(ctx_data);
  621. *params.ctx = nullptr;
  622. gguf_free(ctx);
  623. return nullptr;
  624. }
  625. ggml_set_no_alloc(ctx_data, params.no_alloc);
  626. }
  627. return ctx;
  628. }
  629. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  630. FILE * file = ggml_fopen(fname, "rb");
  631. if (!file) {
  632. GGML_LOG_ERROR("%s: failed to open GGUF file '%s'\n", __func__, fname);
  633. return nullptr;
  634. }
  635. struct gguf_context * result = gguf_init_from_file_impl(file, params);
  636. fclose(file);
  637. return result;
  638. }
  639. void gguf_free(struct gguf_context * ctx) {
  640. if (ctx == nullptr) {
  641. return;
  642. }
  643. delete ctx;
  644. }
  645. const char * gguf_type_name(enum gguf_type type) {
  646. auto it = GGUF_TYPE_NAME.find(type);
  647. return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
  648. }
  649. uint32_t gguf_get_version(const struct gguf_context * ctx) {
  650. return ctx->version;
  651. }
  652. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  653. return ctx->alignment;
  654. }
  655. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  656. return ctx->offset;
  657. }
  658. int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
  659. return ctx->kv.size();
  660. }
  661. int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
  662. // return -1 if key not found
  663. int64_t keyfound = -1;
  664. const int64_t n_kv = gguf_get_n_kv(ctx);
  665. for (int64_t i = 0; i < n_kv; ++i) {
  666. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  667. keyfound = i;
  668. break;
  669. }
  670. }
  671. return keyfound;
  672. }
  673. const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
  674. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  675. return ctx->kv[key_id].get_key().c_str();
  676. }
  677. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
  678. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  679. return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
  680. }
  681. enum gguf_type gguf_get_arr_type(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].is_array);
  684. return ctx->kv[key_id].get_type();
  685. }
  686. const void * gguf_get_arr_data(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_type() != GGUF_TYPE_STRING);
  689. return ctx->kv[key_id].data.data();
  690. }
  691. const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
  692. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  693. GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
  694. return ctx->kv[key_id].data_string[i].c_str();
  695. }
  696. size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
  697. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  698. if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
  699. return ctx->kv[key_id].data_string.size();
  700. }
  701. const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
  702. GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
  703. return ctx->kv[key_id].data.size() / type_size;
  704. }
  705. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
  706. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  707. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  708. return ctx->kv[key_id].get_val<uint8_t>();
  709. }
  710. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
  711. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  712. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  713. return ctx->kv[key_id].get_val<int8_t>();
  714. }
  715. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
  716. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  717. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  718. return ctx->kv[key_id].get_val<uint16_t>();
  719. }
  720. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
  721. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  722. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  723. return ctx->kv[key_id].get_val<int16_t>();
  724. }
  725. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
  726. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  727. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  728. return ctx->kv[key_id].get_val<uint32_t>();
  729. }
  730. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
  731. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  732. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  733. return ctx->kv[key_id].get_val<int32_t>();
  734. }
  735. float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
  736. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  737. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  738. return ctx->kv[key_id].get_val<float>();
  739. }
  740. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
  741. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  742. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  743. return ctx->kv[key_id].get_val<uint64_t>();
  744. }
  745. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
  746. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  747. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  748. return ctx->kv[key_id].get_val<int64_t>();
  749. }
  750. double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
  751. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  752. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  753. return ctx->kv[key_id].get_val<double>();
  754. }
  755. bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
  756. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  757. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  758. return ctx->kv[key_id].get_val<bool>();
  759. }
  760. const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
  761. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  762. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  763. return ctx->kv[key_id].get_val<std::string>().c_str();
  764. }
  765. const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
  766. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  767. GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
  768. GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
  769. return ctx->kv[key_id].data.data();
  770. }
  771. int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
  772. return ctx->info.size();
  773. }
  774. int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  775. // return -1 if tensor not found
  776. int64_t tensor_id = -1;
  777. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  778. for (int64_t i = 0; i < n_tensors; ++i) {
  779. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  780. tensor_id = i;
  781. break;
  782. }
  783. }
  784. return tensor_id;
  785. }
  786. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
  787. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  788. return ctx->info[tensor_id].offset;
  789. }
  790. const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
  791. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  792. return ctx->info[tensor_id].t.name;
  793. }
  794. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
  795. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  796. return ctx->info[tensor_id].t.type;
  797. }
  798. size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
  799. GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
  800. return ggml_nbytes(&ctx->info[tensor_id].t);
  801. }
  802. int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
  803. const int64_t key_id = gguf_find_key(ctx, key);
  804. if (key_id >= 0) {
  805. ctx->kv.erase(ctx->kv.begin() + key_id);
  806. }
  807. return key_id;
  808. }
  809. template<typename T>
  810. static void gguf_check_reserved_keys(const std::string & key, const T val) {
  811. if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
  812. if constexpr (std::is_same<T, uint32_t>::value) {
  813. GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
  814. } else {
  815. GGML_UNUSED(val);
  816. GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
  817. }
  818. }
  819. }
  820. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t 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_i8(struct gguf_context * ctx, const char * key, int8_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_u16(struct gguf_context * ctx, const char * key, uint16_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_i16(struct gguf_context * ctx, const char * key, int16_t 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_u32(struct gguf_context * ctx, const char * key, uint32_t 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_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  846. gguf_check_reserved_keys(key, val);
  847. gguf_remove_key(ctx, key);
  848. ctx->kv.emplace_back(key, val);
  849. }
  850. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  851. gguf_check_reserved_keys(key, val);
  852. gguf_remove_key(ctx, key);
  853. ctx->kv.emplace_back(key, val);
  854. }
  855. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  856. gguf_check_reserved_keys(key, val);
  857. gguf_remove_key(ctx, key);
  858. ctx->kv.emplace_back(key, val);
  859. }
  860. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  861. gguf_check_reserved_keys(key, val);
  862. gguf_remove_key(ctx, key);
  863. ctx->kv.emplace_back(key, val);
  864. }
  865. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  866. gguf_check_reserved_keys(key, val);
  867. gguf_remove_key(ctx, key);
  868. ctx->kv.emplace_back(key, val);
  869. }
  870. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  871. gguf_check_reserved_keys(key, val);
  872. gguf_remove_key(ctx, key);
  873. ctx->kv.emplace_back(key, val);
  874. }
  875. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  876. gguf_check_reserved_keys(key, val);
  877. gguf_remove_key(ctx, key);
  878. ctx->kv.emplace_back(key, std::string(val));
  879. }
  880. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n) {
  881. gguf_check_reserved_keys(key, data);
  882. gguf_remove_key(ctx, key);
  883. const size_t nbytes = n*gguf_type_size(type);
  884. std::vector<int8_t> tmp(nbytes);
  885. if (!tmp.empty()) {
  886. memcpy(tmp.data(), data, nbytes);
  887. }
  888. ctx->kv.emplace_back(key, tmp);
  889. ctx->kv.back().cast(type);
  890. }
  891. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, size_t n) {
  892. gguf_check_reserved_keys(key, data);
  893. gguf_remove_key(ctx, key);
  894. std::vector<std::string> tmp(n);
  895. for (size_t i = 0; i < n; ++i) {
  896. tmp[i] = data[i];
  897. }
  898. ctx->kv.emplace_back(key, tmp);
  899. }
  900. // set or add KV pairs from another context
  901. void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src) {
  902. const int64_t n_kv = gguf_get_n_kv(src);
  903. for (int64_t i = 0; i < n_kv; ++i) {
  904. const struct gguf_kv & kv = src->kv[i];
  905. if (!kv.is_array) {
  906. switch (kv.get_type()) {
  907. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, kv.get_key().c_str(), kv.get_val<uint8_t>()); break;
  908. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, kv.get_key().c_str(), kv.get_val<int8_t>()); break;
  909. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, kv.get_key().c_str(), kv.get_val<uint16_t>()); break;
  910. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, kv.get_key().c_str(), kv.get_val<int16_t>()); break;
  911. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, kv.get_key().c_str(), kv.get_val<uint32_t>()); break;
  912. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, kv.get_key().c_str(), kv.get_val<int32_t>()); break;
  913. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, kv.get_key().c_str(), kv.get_val<float>()); break;
  914. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, kv.get_key().c_str(), kv.get_val<uint64_t>()); break;
  915. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, kv.get_key().c_str(), kv.get_val<int64_t>()); break;
  916. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, kv.get_key().c_str(), kv.get_val<double>()); break;
  917. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, kv.get_key().c_str(), kv.get_val<bool>()); break;
  918. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, kv.get_key().c_str(), kv.get_val<std::string>().c_str()); break;
  919. case GGUF_TYPE_ARRAY:
  920. default: GGML_ABORT("invalid type");
  921. }
  922. continue;
  923. }
  924. const size_t ne = kv.get_ne();
  925. switch (kv.get_type()) {
  926. case GGUF_TYPE_UINT8:
  927. case GGUF_TYPE_INT8:
  928. case GGUF_TYPE_UINT16:
  929. case GGUF_TYPE_INT16:
  930. case GGUF_TYPE_UINT32:
  931. case GGUF_TYPE_INT32:
  932. case GGUF_TYPE_FLOAT32:
  933. case GGUF_TYPE_UINT64:
  934. case GGUF_TYPE_INT64:
  935. case GGUF_TYPE_FLOAT64:
  936. case GGUF_TYPE_BOOL: {
  937. gguf_set_arr_data(ctx, kv.get_key().c_str(), kv.get_type(), kv.data.data(), ne);
  938. } break;
  939. case GGUF_TYPE_STRING: {
  940. std::vector<const char *> tmp(ne);
  941. for (size_t j = 0; j < ne; ++j) {
  942. tmp[j] = kv.data_string[j].c_str();
  943. }
  944. gguf_set_arr_str(ctx, kv.get_key().c_str(), tmp.data(), ne);
  945. } break;
  946. case GGUF_TYPE_ARRAY:
  947. default: GGML_ABORT("invalid type");
  948. }
  949. }
  950. }
  951. void gguf_add_tensor(
  952. struct gguf_context * ctx,
  953. const struct ggml_tensor * tensor) {
  954. GGML_ASSERT(tensor);
  955. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  956. GGML_ABORT("duplicate tensor name: %s", tensor->name);
  957. }
  958. struct gguf_tensor_info ti;
  959. ti.t = *tensor;
  960. ti.offset = ctx->info.empty() ? 0 :
  961. ctx->info.back().offset + GGML_PAD(ggml_nbytes(&ctx->info.back().t), ctx->alignment);
  962. ctx->info.push_back(ti);
  963. }
  964. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  965. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  966. if (tensor_id < 0) {
  967. GGML_ABORT("tensor not found: %s", name);
  968. }
  969. struct ggml_tensor * tensor = &ctx->info[tensor_id].t;
  970. const size_t type_size = ggml_type_size(type);
  971. const int64_t blck_size = ggml_blck_size(type);
  972. tensor->type = type;
  973. GGML_ASSERT(tensor->ne[0] % blck_size == 0 && "tensor row size not divisible by block size of new type");
  974. tensor->nb[0] = type_size;
  975. tensor->nb[1] = tensor->nb[0]*(tensor->ne[0]/blck_size);
  976. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  977. tensor->nb[i] = tensor->nb[i - 1]*tensor->ne[i - 1];
  978. }
  979. // update offsets
  980. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  981. for (int64_t i = tensor_id + 1; i < n_tensors; ++i) {
  982. ctx->info[i].offset = ctx->info[i - 1].offset + GGML_PAD(ggml_nbytes(&ctx->info[i - 1].t), ctx->alignment);
  983. }
  984. }
  985. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data) {
  986. const int64_t tensor_id = gguf_find_tensor(ctx, name);
  987. if (tensor_id < 0) {
  988. GGML_ABORT("tensor not found: %s", name);
  989. }
  990. ctx->info[tensor_id].t.data = (void *)(uintptr_t)data; // double cast suppresses warning about casting away const
  991. }
  992. struct gguf_writer_base {
  993. size_t written_bytes {0u};
  994. ~gguf_writer_base(void) {}
  995. // we bet on devirtualization
  996. virtual void write(int8_t val) = 0;
  997. virtual void write(const std::vector<int8_t> & val) = 0;
  998. virtual void write_tensor_data(const struct gguf_tensor_info & info, size_t offset_data, size_t alignment) = 0;
  999. template <typename T>
  1000. void write(const T & val) {
  1001. for (size_t i = 0; i < sizeof(val); ++i) {
  1002. write(reinterpret_cast<const int8_t *>(&val)[i]);
  1003. }
  1004. }
  1005. void write(const bool & val) {
  1006. const int8_t val8 = val ? 1 : 0;
  1007. write(val8);
  1008. }
  1009. void write(const std::string & val) {
  1010. {
  1011. const uint64_t n = val.length();
  1012. write(n);
  1013. }
  1014. for (size_t i = 0; i < val.length(); ++i) {
  1015. write((val.data())[i]);
  1016. }
  1017. }
  1018. void write(const char * val) {
  1019. write(std::string(val));
  1020. }
  1021. void write(const enum ggml_type & val) {
  1022. write(int32_t(val));
  1023. }
  1024. void write(const enum gguf_type & val) {
  1025. write(int32_t(val));
  1026. }
  1027. void write(const struct gguf_kv & kv) {
  1028. const uint64_t ne = kv.get_ne();
  1029. write(kv.get_key());
  1030. if (kv.is_array) {
  1031. write(GGUF_TYPE_ARRAY);
  1032. write(kv.get_type());
  1033. write(ne);
  1034. } else {
  1035. write(kv.get_type());
  1036. }
  1037. switch (kv.get_type()) {
  1038. case GGUF_TYPE_UINT8:
  1039. case GGUF_TYPE_INT8:
  1040. case GGUF_TYPE_UINT16:
  1041. case GGUF_TYPE_INT16:
  1042. case GGUF_TYPE_UINT32:
  1043. case GGUF_TYPE_INT32:
  1044. case GGUF_TYPE_FLOAT32:
  1045. case GGUF_TYPE_UINT64:
  1046. case GGUF_TYPE_INT64:
  1047. case GGUF_TYPE_FLOAT64: {
  1048. write(kv.data);
  1049. } break;
  1050. case GGUF_TYPE_BOOL: {
  1051. for (size_t i = 0; i < ne; ++i) {
  1052. write(kv.get_val<bool>(i));
  1053. }
  1054. } break;
  1055. case GGUF_TYPE_STRING: {
  1056. for (size_t i = 0; i < ne; ++i) {
  1057. write(kv.get_val<std::string>(i));
  1058. }
  1059. } break;
  1060. case GGUF_TYPE_ARRAY:
  1061. default: GGML_ABORT("invalid type");
  1062. }
  1063. }
  1064. void write_tensor_meta(const struct gguf_tensor_info & info) {
  1065. write(info.t.name);
  1066. const uint32_t n_dims = ggml_n_dims(&info.t);
  1067. write(n_dims);
  1068. for (uint32_t j = 0; j < n_dims; ++j) {
  1069. write(info.t.ne[j]);
  1070. }
  1071. write(info.t.type);
  1072. write(info.offset);
  1073. }
  1074. void pad(const size_t alignment) {
  1075. while (written_bytes % alignment != 0) {
  1076. const int8_t zero = 0;
  1077. write(zero);
  1078. }
  1079. }
  1080. };
  1081. // vector buffer based writer
  1082. struct gguf_writer_buf final : public gguf_writer_base {
  1083. std::vector<int8_t> & buf;
  1084. gguf_writer_buf(std::vector<int8_t> & buf) : buf(buf) {}
  1085. using gguf_writer_base::write;
  1086. void write(const int8_t val) override {
  1087. buf.push_back(val);
  1088. written_bytes++;
  1089. }
  1090. void write(const std::vector<int8_t> & val) override {
  1091. buf.insert(buf.end(), val.begin(), val.end());
  1092. written_bytes += val.size();
  1093. }
  1094. void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) override {
  1095. GGML_ASSERT(buf.size() - offset_data == info.offset);
  1096. GGML_ASSERT(ggml_is_contiguous(&info.t));
  1097. const size_t offset = buf.size();
  1098. const size_t nbytes = ggml_nbytes(&info.t);
  1099. buf.resize(offset + nbytes);
  1100. if (info.t.buffer) {
  1101. ggml_backend_tensor_get(&info.t, buf.data() + offset, 0, nbytes);
  1102. } else {
  1103. GGML_ASSERT(info.t.data);
  1104. memcpy(buf.data() + offset, info.t.data, nbytes);
  1105. }
  1106. written_bytes += nbytes;
  1107. pad(alignment);
  1108. }
  1109. };
  1110. // file based writer
  1111. struct gguf_writer_file final : public gguf_writer_base {
  1112. FILE * file;
  1113. gguf_writer_file(FILE* file) : file(file) {}
  1114. using gguf_writer_base::write;
  1115. void write(const int8_t val) override {
  1116. const auto real_val = static_cast<uint8_t>(val);
  1117. const auto ret = fputc(real_val, file);
  1118. written_bytes++;
  1119. if (ret != real_val) {
  1120. throw std::runtime_error("unexpected fputc result '" + std::to_string(ret) + "' instead of '" + std::to_string((int)real_val) + "'");
  1121. }
  1122. }
  1123. void write(const std::vector<int8_t> & val) override {
  1124. const auto ret = fwrite(val.data(), 1, val.size(), file);
  1125. written_bytes += val.size();
  1126. if (ret != val.size()) {
  1127. throw std::runtime_error("unexpected fwrite number of bytes written, '" + std::to_string(ret) + "' instead of '" + std::to_string(val.size()) + "'");
  1128. }
  1129. }
  1130. void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) override {
  1131. GGML_ASSERT(written_bytes - offset_data == info.offset);
  1132. GGML_ASSERT(ggml_is_contiguous(&info.t));
  1133. const size_t nbytes = ggml_nbytes(&info.t);
  1134. std::vector<int8_t> buf(nbytes);
  1135. if (info.t.buffer) {
  1136. ggml_backend_tensor_get(&info.t, buf.data(), 0, nbytes);
  1137. } else {
  1138. GGML_ASSERT(info.t.data);
  1139. memcpy(buf.data(), info.t.data, nbytes);
  1140. }
  1141. write(buf);
  1142. pad(alignment);
  1143. }
  1144. };
  1145. template <typename writer_t>
  1146. static void gguf_write_out(const struct gguf_context * ctx, writer_t & gw, bool only_meta) {
  1147. const int64_t n_kv = gguf_get_n_kv(ctx);
  1148. const int64_t n_tensors = gguf_get_n_tensors(ctx);
  1149. // write header
  1150. gw.write(GGUF_MAGIC[0]);
  1151. gw.write(GGUF_MAGIC[1]);
  1152. gw.write(GGUF_MAGIC[2]);
  1153. gw.write(GGUF_MAGIC[3]);
  1154. gw.write(ctx->version);
  1155. gw.write(n_tensors);
  1156. gw.write(n_kv);
  1157. // write key-value pairs
  1158. for (int64_t i = 0; i < n_kv; ++i) {
  1159. gw.write(ctx->kv[i]);
  1160. }
  1161. // write tensor info
  1162. for (int64_t i = 0; i < n_tensors; ++i) {
  1163. gw.write_tensor_meta(ctx->info[i]);
  1164. }
  1165. // we require the data section to be aligned
  1166. gw.pad(ctx->alignment);
  1167. if (only_meta) {
  1168. return;
  1169. }
  1170. const size_t offset_data = gw.written_bytes;
  1171. // write tensor data
  1172. for (int64_t i = 0; i < n_tensors; ++i) {
  1173. gw.write_tensor_data(ctx->info[i], offset_data, ctx->alignment);
  1174. }
  1175. }
  1176. void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta) {
  1177. gguf_writer_buf gw(buf);
  1178. gguf_write_out(ctx, gw, only_meta);
  1179. }
  1180. bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  1181. FILE * file = ggml_fopen(fname, "wb");
  1182. if (!file) {
  1183. GGML_LOG_ERROR("%s: failed to open file '%s' for writing GGUF data\n", __func__, fname);
  1184. return false;
  1185. }
  1186. try {
  1187. gguf_writer_file gw(file);
  1188. gguf_write_out(ctx, gw, only_meta);
  1189. } catch (const std::runtime_error& ex) {
  1190. GGML_LOG_ERROR("%s: failed to write GGUF data into '%s': %s\n", __func__, fname, ex.what());
  1191. fclose(file);
  1192. return false;
  1193. }
  1194. fclose(file);
  1195. return true;
  1196. }
  1197. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  1198. // only return size
  1199. std::vector<int8_t> buf;
  1200. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1201. return buf.size();
  1202. }
  1203. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  1204. std::vector<int8_t> buf;
  1205. gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
  1206. memcpy(data, buf.data(), buf.size());
  1207. }