llama-model-loader.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. #include "llama-model-loader.h"
  2. #include "ggml.h"
  3. #include <array>
  4. #include <cinttypes>
  5. #include <cstring>
  6. #include <future>
  7. static const size_t kiB = 1024;
  8. static const size_t MiB = 1024*kiB;
  9. static const size_t GiB = 1024*MiB;
  10. const char * llama_file_version_name(llama_fver version) {
  11. switch (version) {
  12. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  13. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  14. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  15. }
  16. return "unknown";
  17. }
  18. static std::string llama_model_ftype_name(llama_ftype ftype) {
  19. if (ftype & LLAMA_FTYPE_GUESSED) {
  20. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  21. }
  22. switch (ftype) {
  23. case LLAMA_FTYPE_ALL_F32: return "all F32";
  24. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  25. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  26. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  27. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  28. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  29. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  30. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  31. case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return "MXFP4 MoE";
  32. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  33. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  34. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  35. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  36. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  37. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  38. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  39. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  40. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  41. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  42. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  43. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  44. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  45. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  46. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  47. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  48. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  49. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  50. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  51. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  52. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  53. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  54. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  55. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  56. default: return "unknown, may not work";
  57. }
  58. }
  59. // return a list of splits for a given path
  60. // for example, given "<name>-00002-of-00004.gguf", returns list of all 4 splits
  61. static std::vector<std::string> llama_get_list_splits(const std::string & path, const int idx, const int n_split) {
  62. std::vector<std::string> paths;
  63. std::string split_prefix;
  64. std::vector<char> buf(llama_path_max(), 0);
  65. {
  66. int ret = llama_split_prefix(buf.data(), buf.size(), path.c_str(), idx, n_split);
  67. if (!ret) {
  68. throw std::runtime_error(format("invalid split file name: %s", path.c_str()));
  69. }
  70. split_prefix = std::string(buf.data(), ret);
  71. }
  72. if (split_prefix.empty()) {
  73. throw std::runtime_error(format("invalid split file: %s", path.c_str()));
  74. }
  75. for (int idx = 0; idx < n_split; ++idx) {
  76. int ret = llama_split_path(buf.data(), buf.size(), split_prefix.c_str(), idx, n_split);
  77. paths.push_back(std::string(buf.data(), ret));
  78. }
  79. return paths;
  80. }
  81. namespace GGUFMeta {
  82. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int64_t)>
  83. struct GKV_Base_Type {
  84. static constexpr gguf_type gt = gt_;
  85. static T getter(const gguf_context * ctx, const int kid) {
  86. return gfun(ctx, kid);
  87. }
  88. };
  89. template<typename T> struct GKV_Base;
  90. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  91. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  92. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  93. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  94. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  95. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  96. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  97. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  98. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  99. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  100. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  101. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  102. template<> struct GKV_Base<std::string> {
  103. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  104. static std::string getter(const gguf_context * ctx, const int kid) {
  105. return gguf_get_val_str(ctx, kid);
  106. }
  107. };
  108. struct ArrayInfo {
  109. const gguf_type gt;
  110. const size_t length;
  111. const void * data;
  112. };
  113. template<> struct GKV_Base<ArrayInfo> {
  114. public:
  115. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  116. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  117. const enum gguf_type arr_type = gguf_get_arr_type(ctx, k);
  118. return ArrayInfo {
  119. arr_type,
  120. size_t(gguf_get_arr_n(ctx, k)),
  121. arr_type == GGUF_TYPE_STRING ? nullptr : gguf_get_arr_data(ctx, k),
  122. };
  123. }
  124. };
  125. template<typename T>
  126. class GKV : public GKV_Base<T> {
  127. GKV() = delete;
  128. public:
  129. static T get_kv(const gguf_context * ctx, const int k) {
  130. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  131. if (kt != GKV::gt) {
  132. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  133. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  134. }
  135. return GKV::getter(ctx, k);
  136. }
  137. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  138. switch (ty) {
  139. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  140. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  141. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  142. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  143. }
  144. return "unknown";
  145. }
  146. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  147. if (!ovrd) { return false; }
  148. if (ovrd->tag == expected_type) {
  149. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  150. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  151. switch (ovrd->tag) {
  152. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  153. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  154. } break;
  155. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  156. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  157. } break;
  158. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  159. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  160. } break;
  161. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  162. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  163. } break;
  164. default:
  165. // Shouldn't be possible to end up here, but just in case...
  166. throw std::runtime_error(
  167. format("Unsupported attempt to override %s type for metadata key %s\n",
  168. override_type_to_str(ovrd->tag), ovrd->key));
  169. }
  170. return true;
  171. }
  172. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  173. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  174. return false;
  175. }
  176. template<typename OT>
  177. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  178. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  179. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  180. target = ovrd->val_bool;
  181. return true;
  182. }
  183. return false;
  184. }
  185. template<typename OT>
  186. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  187. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  188. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  189. target = ovrd->val_i64;
  190. return true;
  191. }
  192. return false;
  193. }
  194. template<typename OT>
  195. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  196. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  197. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  198. target = ovrd->val_f64;
  199. return true;
  200. }
  201. return false;
  202. }
  203. template<typename OT>
  204. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  205. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  206. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  207. target = ovrd->val_str;
  208. return true;
  209. }
  210. return false;
  211. }
  212. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  213. if (try_override<T>(target, ovrd)) {
  214. return true;
  215. }
  216. if (k < 0) { return false; }
  217. target = get_kv(ctx, k);
  218. return true;
  219. }
  220. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  221. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  222. }
  223. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  224. return set(ctx, key.c_str(), target, ovrd);
  225. }
  226. };
  227. }
  228. template<typename T>
  229. typename std::enable_if<std::is_integral<T>::value, bool>::type
  230. llama_model_loader::get_arr_n(const std::string & key, T & result, bool required) {
  231. const int kid = gguf_find_key(meta.get(), key.c_str());
  232. if (kid < 0) {
  233. if (required) {
  234. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  235. }
  236. return false;
  237. }
  238. struct GGUFMeta::ArrayInfo arr_info =
  239. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  240. result = arr_info.length;
  241. return true;
  242. }
  243. template<typename T>
  244. typename std::enable_if<std::is_integral<T>::value, bool>::type
  245. llama_model_loader::get_arr_n(enum llm_kv kid, T & result, bool required) {
  246. return get_arr_n(llm_kv(kid), result, required);
  247. }
  248. template bool llama_model_loader::get_arr_n(enum llm_kv kid, uint32_t & result, bool required);
  249. template<typename T>
  250. bool llama_model_loader::get_arr(const std::string & key, std::vector<T> & result, bool required) {
  251. const gguf_context * ctx = meta.get();
  252. const int kid = gguf_find_key(ctx, key.c_str());
  253. if (kid < 0 || gguf_get_kv_type(ctx, kid) != GGUF_TYPE_ARRAY) {
  254. if (required) {
  255. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  256. }
  257. return false;
  258. }
  259. struct GGUFMeta::ArrayInfo arr_info =
  260. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx, kid);
  261. switch (arr_info.gt) {
  262. case GGUF_TYPE_UINT32:
  263. case GGUF_TYPE_INT32: GGML_ASSERT((std::is_same<T, int32_t>::value) ||
  264. (std::is_same<T, uint32_t>::value)); break;
  265. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  266. case GGUF_TYPE_STRING: GGML_ASSERT((std::is_same<T, std::string>::value)); break;
  267. default:
  268. throw std::runtime_error(format("%s is not a string/float32/uint32/int32 array", key.c_str()));
  269. }
  270. if constexpr (std::is_same<T, std::string>::value) {
  271. const size_t n_items = gguf_get_arr_n(ctx, kid);
  272. result.clear();
  273. for (size_t i = 0; i < n_items; i++) {
  274. const T value = gguf_get_arr_str(ctx, kid, i);
  275. result.emplace_back(value);
  276. }
  277. } else {
  278. result.resize(arr_info.length);
  279. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  280. }
  281. return true;
  282. }
  283. template<typename T, size_t N_MAX>
  284. bool llama_model_loader::get_arr(const std::string & key, std::array<T, N_MAX> & result, bool required) {
  285. const gguf_context * ctx = meta.get();
  286. const int kid = gguf_find_key(ctx, key.c_str());
  287. if (kid < 0 || gguf_get_kv_type(ctx, kid) != GGUF_TYPE_ARRAY) {
  288. if (required) {
  289. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  290. }
  291. return false;
  292. }
  293. struct GGUFMeta::ArrayInfo arr_info =
  294. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx, kid);
  295. switch (arr_info.gt) {
  296. case GGUF_TYPE_UINT32:
  297. case GGUF_TYPE_INT32: GGML_ASSERT((std::is_same<T, int32_t>::value) ||
  298. (std::is_same<T, uint32_t>::value)); break;
  299. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  300. case GGUF_TYPE_STRING: GGML_ASSERT((std::is_same<T, std::string>::value)); break;
  301. default:
  302. throw std::runtime_error(format("%s is not a string/float32/uint32/int32 array", key.c_str()));
  303. }
  304. if (arr_info.length > N_MAX) {
  305. throw std::runtime_error(format("array length %u for key %s exceeds max %u", (uint32_t) arr_info.length, key.c_str(), (uint32_t) N_MAX));
  306. }
  307. if constexpr (std::is_same<T, std::string>::value) {
  308. const size_t n_items = gguf_get_arr_n(ctx, kid);
  309. for (size_t i = 0; i < n_items; i++) {
  310. const T value = gguf_get_arr_str(ctx, kid, i);
  311. result[i] = value;
  312. }
  313. } else {
  314. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  315. }
  316. return true;
  317. }
  318. template<typename T>
  319. bool llama_model_loader::get_arr(enum llm_kv kid, T & result, bool required) {
  320. return get_arr(llm_kv(kid), result, required);
  321. }
  322. template bool llama_model_loader::get_arr<std::vector<std::string>>(enum llm_kv kid, std::vector<std::string> & result, bool required);
  323. template<typename T>
  324. bool llama_model_loader::get_key(const std::string & key, T & result, bool required) {
  325. auto it = kv_overrides.find(key);
  326. const struct llama_model_kv_override * override =
  327. it != kv_overrides.end() ? &it->second : nullptr;
  328. const bool found = GGUFMeta::GKV<T>::set(meta.get(), key, result, override);
  329. if (required && !found) {
  330. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  331. }
  332. return found;
  333. }
  334. template<typename T>
  335. bool llama_model_loader::get_key(enum llm_kv kid, T & result, bool required) {
  336. return get_key(llm_kv(kid), result, required);
  337. }
  338. template bool llama_model_loader::get_key<bool> (enum llm_kv kid, bool & result, bool required);
  339. template bool llama_model_loader::get_key<float> (enum llm_kv kid, float & result, bool required);
  340. template bool llama_model_loader::get_key<uint32_t> (enum llm_kv kid, uint32_t & result, bool required);
  341. template bool llama_model_loader::get_key<std::string>(enum llm_kv kid, std::string & result, bool required);
  342. template<>
  343. bool llama_model_loader::get_key(enum llm_kv kid, enum llama_pooling_type & result, bool required) {
  344. uint32_t tmp;
  345. const bool found = get_key(kid, tmp, required);
  346. if (found) {
  347. result = (enum llama_pooling_type) tmp;
  348. } else {
  349. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  350. }
  351. return found;
  352. }
  353. // get array of n <= N_MAX elements, or a single element repeated n times
  354. template<typename T, size_t N_MAX>
  355. bool llama_model_loader::get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, bool required) {
  356. const int kid = gguf_find_key(meta.get(), key.c_str());
  357. if (kid < 0) {
  358. if (required) {
  359. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  360. }
  361. return false;
  362. }
  363. if (n > N_MAX) {
  364. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  365. }
  366. if (gguf_get_kv_type(meta.get(), kid) == GGUF_TYPE_ARRAY) {
  367. struct GGUFMeta::ArrayInfo arr_info =
  368. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  369. if (n != arr_info.length) {
  370. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  371. }
  372. return get_arr(key, result, required);
  373. }
  374. T value;
  375. bool ok = get_key(key, value, required);
  376. if (!ok) {
  377. return false;
  378. }
  379. for (uint32_t i = 0; i < n; i++) {
  380. result[i] = value;
  381. }
  382. return true;
  383. }
  384. template<typename T>
  385. bool llama_model_loader::get_key_or_arr(enum llm_kv kid, T & result, uint32_t n, bool required) {
  386. return get_key_or_arr(llm_kv(kid), result, n, required);
  387. }
  388. // TODO: this is not very clever - figure out something better
  389. template bool llama_model_loader::get_key_or_arr<std::array<int, 4>>(enum llm_kv kid, std::array<int, 4> & result, uint32_t n, bool required);
  390. template bool llama_model_loader::get_key_or_arr<std::array<uint32_t, 512>>(enum llm_kv kid, std::array<uint32_t, 512> & result, uint32_t n, bool required);
  391. llama_model_loader::llama_model_loader(
  392. const std::string & fname,
  393. std::vector<std::string> & splits,
  394. bool use_mmap,
  395. bool check_tensors,
  396. const llama_model_kv_override * param_overrides_p,
  397. const llama_model_tensor_buft_override * param_tensor_buft_overrides_p) {
  398. int trace = 0;
  399. if (getenv("LLAMA_TRACE")) {
  400. trace = atoi(getenv("LLAMA_TRACE"));
  401. }
  402. if (param_overrides_p != nullptr) {
  403. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  404. kv_overrides.insert({std::string(p->key), *p});
  405. }
  406. }
  407. tensor_buft_overrides = param_tensor_buft_overrides_p;
  408. // Load the main GGUF
  409. struct ggml_context * ctx = NULL;
  410. struct gguf_init_params params = {
  411. /*.no_alloc = */ true,
  412. /*.ctx = */ &ctx,
  413. };
  414. meta.reset(gguf_init_from_file(fname.c_str(), params));
  415. if (!meta) {
  416. throw std::runtime_error(format("%s: failed to load model from %s", __func__, fname.c_str()));
  417. }
  418. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  419. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  420. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  421. contexts.emplace_back(ctx);
  422. // Save tensors data offset of the main file.
  423. // For subsidiary files, `meta` tensor data offset must not be used,
  424. // so we build a unified tensors index for weights.
  425. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  426. std::string tensor_name = std::string(cur->name);
  427. // make sure there is no duplicated tensor names
  428. if (weights_map.find(tensor_name) != weights_map.end()) {
  429. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  430. }
  431. n_elements += ggml_nelements(cur);
  432. n_bytes += ggml_nbytes(cur);
  433. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, meta.get(), cur));
  434. }
  435. uint16_t n_split = 0;
  436. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  437. // Load additional GGML contexts
  438. if (n_split > 1) {
  439. // make sure the main file is loaded first
  440. uint16_t idx = 0;
  441. const std::string kv_split_no = llm_kv(LLM_KV_SPLIT_NO);
  442. get_key(kv_split_no, idx);
  443. if (idx != 0) {
  444. throw std::runtime_error(format("illegal split file idx: %d (file: %s), model must be loaded with the first split", idx, fname.c_str()));
  445. }
  446. // generate list of splits if needed
  447. if (splits.empty()) {
  448. splits = llama_get_list_splits(fname, idx, n_split);
  449. }
  450. // in case user give a custom list of splits, check if it matches the expected number
  451. if (n_split != (uint16_t)splits.size()) {
  452. throw std::runtime_error(format("invalid split count, given: %zu splits, but expected %d", splits.size(), n_split));
  453. }
  454. if (trace > 0) {
  455. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  456. }
  457. // load other splits
  458. for (idx = 1; idx < n_split; idx++) {
  459. const char * fname_split = splits[idx].c_str();
  460. struct gguf_init_params split_params = {
  461. /*.no_alloc = */ true,
  462. /*.ctx = */ &ctx,
  463. };
  464. gguf_context_ptr ctx_gguf { gguf_init_from_file(fname_split, split_params) };
  465. if (!ctx_gguf) {
  466. throw std::runtime_error(format("%s: failed to load GGUF split from %s", __func__, fname_split));
  467. }
  468. // check idx
  469. {
  470. const int kid = gguf_find_key(ctx_gguf.get(), kv_split_no.c_str());
  471. if (kid < 0) {
  472. throw std::runtime_error(format("missing key %s in GGUF split %s", kv_split_no.c_str(), fname_split));
  473. }
  474. int idx_gguf = gguf_get_val_u16(ctx_gguf.get(), kid);
  475. if (idx_gguf != idx) {
  476. throw std::runtime_error(format("invalid split file idx: %d (file: %s), expected %d", idx_gguf, fname_split, idx));
  477. }
  478. }
  479. files.emplace_back(new llama_file(fname_split, "rb"));
  480. contexts.emplace_back(ctx);
  481. // Save tensors data offset info of the shard.
  482. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  483. std::string tensor_name = std::string(cur->name);
  484. // make sure there is no duplicated tensor names
  485. if (weights_map.find(tensor_name) != weights_map.end()) {
  486. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  487. }
  488. n_elements += ggml_nelements(cur);
  489. n_bytes += ggml_nbytes(cur);
  490. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), idx, ctx_gguf.get(), cur));
  491. }
  492. }
  493. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  494. // sanity check
  495. {
  496. const int n_tensors_loaded = (int) weights_map.size();
  497. if (n_tensors != n_tensors_loaded) {
  498. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  499. }
  500. }
  501. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  502. }
  503. n_kv = gguf_get_n_kv(meta.get());
  504. n_tensors = weights_map.size();
  505. fver = (enum llama_fver) gguf_get_version(meta.get());
  506. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  507. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  508. // determine file type based on the number of tensors for each quantization and print meta data
  509. // TODO: make optional
  510. {
  511. std::map<enum ggml_type, uint32_t> n_type;
  512. uint32_t n_type_max = 0;
  513. enum ggml_type type_max = GGML_TYPE_F32;
  514. for (const auto & it : weights_map) {
  515. const llama_tensor_weight & w = it.second;
  516. const ggml_tensor * tensor = w.tensor;
  517. enum ggml_type type = tensor->type;
  518. n_type[type]++;
  519. if (n_type_max < n_type[type]) {
  520. n_type_max = n_type[type];
  521. type_max = type;
  522. }
  523. if (trace > 0) {
  524. const uint16_t sid = w.idx;
  525. LLAMA_LOG_INFO("%s: - tensor split %2d: %32s %-8s [ %s ] %8.2f MiB\n", __func__,
  526. sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str(),
  527. ggml_nbytes(tensor)/1024.0f/1024.0f);
  528. }
  529. }
  530. switch (type_max) {
  531. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  532. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  533. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  534. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  535. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  536. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  537. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  538. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  539. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  540. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  541. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  542. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  543. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  544. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  545. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  546. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  547. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  548. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  549. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  550. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  551. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  552. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  553. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  554. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  555. default:
  556. {
  557. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  558. ftype = LLAMA_FTYPE_ALL_F32;
  559. } break;
  560. }
  561. // this is a way to mark that we have "guessed" the file type
  562. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  563. {
  564. uint32_t ftype_val = 0;
  565. if (get_key(LLM_KV_GENERAL_FILE_TYPE, ftype_val, false)) {
  566. ftype = (llama_ftype) ftype_val;
  567. }
  568. }
  569. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  570. for (int i = 0; i < n_kv; i++) {
  571. const char * name = gguf_get_key(meta.get(), i);
  572. const enum gguf_type type = gguf_get_kv_type(meta.get(), i);
  573. const std::string type_name =
  574. type == GGUF_TYPE_ARRAY
  575. ? format("%s[%s,%zu]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta.get(), i)), gguf_get_arr_n(meta.get(), i))
  576. : gguf_type_name(type);
  577. std::string value = gguf_kv_to_str(meta.get(), i);
  578. const size_t MAX_VALUE_LEN = 40;
  579. if (value.size() > MAX_VALUE_LEN) {
  580. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  581. }
  582. replace_all(value, "\n", "\\n");
  583. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  584. }
  585. // print type counts
  586. for (auto & kv : n_type) {
  587. if (kv.second == 0) {
  588. continue;
  589. }
  590. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  591. }
  592. }
  593. if (!llama_mmap::SUPPORTED) {
  594. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  595. use_mmap = false;
  596. }
  597. this->use_mmap = use_mmap;
  598. this->check_tensors = check_tensors;
  599. }
  600. std::string llama_model_loader::get_arch_name() const {
  601. return arch_name;
  602. }
  603. enum llm_arch llama_model_loader::get_arch() const {
  604. return llm_kv.arch;
  605. }
  606. const llama_model_loader::llama_tensor_weight * llama_model_loader::get_weight(const char * name) const {
  607. auto pos = weights_map.find(name);
  608. if (pos != weights_map.end()) {
  609. return &pos->second;
  610. }
  611. return nullptr;
  612. }
  613. const llama_model_loader::llama_tensor_weight & llama_model_loader::require_weight(const char * name) const {
  614. const llama_tensor_weight * weight = get_weight(name);
  615. if (!weight) {
  616. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  617. }
  618. return *weight;
  619. }
  620. struct ggml_tensor * llama_model_loader::get_tensor_meta(const char * name) const {
  621. const auto * weight = get_weight(name);
  622. if (!weight) {
  623. return nullptr;
  624. }
  625. return weight->tensor;
  626. }
  627. struct ggml_tensor * llama_model_loader::require_tensor_meta(const std::string & name) const {
  628. struct ggml_tensor * tensor = get_tensor_meta(name.c_str());
  629. if (!tensor) {
  630. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  631. }
  632. return tensor;
  633. }
  634. const struct ggml_tensor * llama_model_loader::check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  635. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  636. if (cur == NULL) {
  637. if (!required) {
  638. return NULL;
  639. }
  640. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  641. }
  642. {
  643. bool is_ok = true;
  644. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  645. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  646. is_ok = false;
  647. break;
  648. }
  649. }
  650. if (!is_ok) {
  651. throw std::runtime_error(
  652. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  653. __func__, name.c_str(),
  654. llama_format_tensor_shape(ne).c_str(),
  655. llama_format_tensor_shape(cur).c_str()));
  656. }
  657. }
  658. return cur;
  659. }
  660. struct ggml_tensor * llama_model_loader::create_tensor(struct ggml_context * ctx, const std::string & name, const std::initializer_list<int64_t> & ne, int flags) {
  661. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  662. if (cur == NULL) {
  663. return NULL;
  664. }
  665. bool duplicated = flags & TENSOR_DUPLICATED;
  666. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  667. ggml_set_name(tensor, ggml_get_name(cur));
  668. if (duplicated) {
  669. size_data += ggml_nbytes(cur);
  670. } else {
  671. n_created++;
  672. }
  673. return tensor;
  674. }
  675. struct ggml_tensor * llama_model_loader::create_tensor_as_view(struct ggml_context * ctx, struct ggml_tensor * base, const std::string & name, const std::initializer_list<int64_t> & ne, size_t offset, bool required) {
  676. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  677. if (cur == NULL) {
  678. return NULL;
  679. }
  680. if (cur->type != base->type) {
  681. throw std::runtime_error(format("%s: tensor '%s' has wrong type; expected %s, got %s", __func__, name.c_str(), ggml_type_name(base->type), ggml_type_name(cur->type)));
  682. }
  683. std::array<int64_t, GGML_MAX_DIMS> dims;
  684. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  685. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  686. }
  687. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  688. dims[0], dims[1], dims[2], dims[3],
  689. cur->nb[1], cur->nb[2], cur->nb[3],
  690. offset);
  691. ggml_set_name(tensor, name.c_str());
  692. n_created++;
  693. return tensor;
  694. }
  695. void llama_model_loader::done_getting_tensors() const {
  696. if (n_created != n_tensors) {
  697. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  698. }
  699. }
  700. void llama_model_loader::init_mappings(bool prefetch, llama_mlocks * mlock_mmaps) {
  701. if (use_mmap) {
  702. mappings.reserve(files.size());
  703. mmaps_used.reserve(files.size());
  704. for (const auto & file : files) {
  705. bool is_numa = false;
  706. auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  707. if (dev) {
  708. auto * reg = ggml_backend_dev_backend_reg(dev);
  709. auto * is_numa_fn = (decltype(ggml_is_numa) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_is_numa");
  710. if (is_numa_fn) {
  711. is_numa = is_numa_fn();
  712. }
  713. }
  714. std::unique_ptr<llama_mmap> mapping = std::make_unique<llama_mmap>(file.get(), prefetch ? -1 : 0, is_numa);
  715. mmaps_used.emplace_back(mapping->size(), 0);
  716. if (mlock_mmaps) {
  717. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  718. mlock_mmap->init(mapping->addr());
  719. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  720. }
  721. mappings.emplace_back(std::move(mapping));
  722. }
  723. }
  724. // compute the total size of all tensors for progress reporting
  725. for (const auto & it : weights_map) {
  726. size_data += ggml_nbytes(it.second.tensor);
  727. }
  728. }
  729. void llama_model_loader::get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  730. GGML_ASSERT(!mappings.empty());
  731. const auto & mapping = mappings.at(idx);
  732. *first = mapping->size();
  733. *last = 0;
  734. *addr = mapping->addr();
  735. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  736. const auto * weight = get_weight(ggml_get_name(tensor));
  737. if (!weight || weight->idx != idx) {
  738. continue;
  739. }
  740. *first = std::min(*first, weight->offs);
  741. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  742. }
  743. }
  744. void llama_model_loader::load_data_for(struct ggml_tensor * cur) const {
  745. const auto & w = require_weight(ggml_get_name(cur));
  746. if (use_mmap) {
  747. const auto & mapping = mappings.at(w.idx);
  748. if (cur->data == nullptr) {
  749. cur->data = (uint8_t *)mapping->addr() + w.offs;
  750. } else {
  751. memcpy(cur->data, (uint8_t *)mapping->addr() + w.offs, ggml_nbytes(cur));
  752. }
  753. } else {
  754. GGML_ASSERT(cur->data != nullptr);
  755. GGML_ASSERT(w.idx < files.size());
  756. const auto & file = files.at(w.idx);
  757. file->seek(w.offs, SEEK_SET);
  758. file->read_raw(cur->data, ggml_nbytes(cur));
  759. }
  760. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  761. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  762. }
  763. }
  764. bool llama_model_loader::load_all_data(
  765. struct ggml_context * ctx,
  766. llama_buf_map & bufs,
  767. llama_mlocks * lmlocks,
  768. llama_progress_callback progress_callback,
  769. void * progress_callback_user_data) {
  770. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  771. std::vector<no_init<uint8_t>> read_buf;
  772. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  773. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  774. // NVMe raid configurations might require more / larger buffers.
  775. constexpr size_t n_buffers = 4;
  776. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  777. std::vector<ggml_backend_buffer_t> host_buffers;
  778. std::vector<ggml_backend_event_t> events;
  779. std::vector<void *> host_ptrs;
  780. size_t buffer_idx = 0; // buffer to use for async loads
  781. ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t {
  782. if (use_mmap || check_tensors) {
  783. return nullptr;
  784. }
  785. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  786. // First determine if the backend supports the necessary features for async uploads.
  787. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  788. if (!buf) {
  789. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func);
  790. return nullptr;
  791. }
  792. auto * buft = ggml_backend_buffer_get_type(buf);
  793. auto * dev = ggml_backend_buft_get_device(buft);
  794. if (!dev) {
  795. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func,
  796. ggml_backend_buft_name(buft));
  797. return nullptr;
  798. }
  799. if (buft != ggml_backend_dev_buffer_type(dev)) {
  800. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func,
  801. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  802. return nullptr;
  803. }
  804. ggml_backend_dev_props props;
  805. ggml_backend_dev_get_props(dev, &props);
  806. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  807. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func,
  808. ggml_backend_dev_name(dev));
  809. return nullptr;
  810. }
  811. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  812. if (!host_buft) {
  813. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func,
  814. ggml_backend_dev_name(dev));
  815. return nullptr;
  816. }
  817. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  818. for (size_t idx = 0; idx < n_buffers; ++idx) {
  819. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  820. if (!buf) {
  821. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", func,
  822. ggml_backend_dev_name(dev));
  823. return nullptr;
  824. }
  825. host_buffers.emplace_back(buf);
  826. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  827. auto * event = ggml_backend_event_new(dev);
  828. if (!event) {
  829. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", func,
  830. ggml_backend_dev_name(dev));
  831. return nullptr;
  832. }
  833. events.emplace_back(event);
  834. }
  835. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  836. if (!backend) {
  837. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", func,
  838. ggml_backend_dev_name(dev));
  839. return nullptr;
  840. }
  841. return backend;
  842. }(__func__);
  843. if (upload_backend) {
  844. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  845. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  846. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  847. ggml_backend_name(upload_backend));
  848. }
  849. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  850. const auto * weight = get_weight(ggml_get_name(cur));
  851. if (weight == nullptr) {
  852. // this can happen with split experts models
  853. continue;
  854. }
  855. if (progress_callback) {
  856. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  857. return false;
  858. }
  859. }
  860. size_t n_size = ggml_nbytes(cur);
  861. if (use_mmap) {
  862. const auto & mapping = mappings.at(weight->idx);
  863. ggml_backend_buffer_t buf_mmap = nullptr;
  864. if (bufs.count(weight->idx)) {
  865. buf_mmap = bufs.at(weight->idx);
  866. }
  867. uint8_t * data = (uint8_t *) mapping->addr() + weight->offs;
  868. if (check_tensors) {
  869. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  870. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  871. }));
  872. }
  873. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  874. if (buf_mmap && cur->data == nullptr) {
  875. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  876. if (lmlocks) {
  877. const auto & lmlock = lmlocks->at(weight->idx);
  878. lmlock->grow_to(weight->offs + n_size);
  879. }
  880. auto & mmap_used = mmaps_used[weight->idx];
  881. mmap_used.first = std::min(mmap_used.first, weight->offs);
  882. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  883. } else {
  884. ggml_backend_tensor_set(cur, data, 0, n_size);
  885. }
  886. } else {
  887. const auto & file = files.at(weight->idx);
  888. if (ggml_backend_buffer_is_host(cur->buffer)) {
  889. file->seek(weight->offs, SEEK_SET);
  890. file->read_raw(cur->data, n_size);
  891. if (check_tensors) {
  892. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  893. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  894. }));
  895. }
  896. } else {
  897. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  898. if (upload_backend) {
  899. file->seek(weight->offs, SEEK_SET);
  900. size_t bytes_read = 0;
  901. while (bytes_read < n_size) {
  902. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  903. ggml_backend_event_synchronize(events[buffer_idx]);
  904. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  905. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  906. ggml_backend_event_record(events[buffer_idx], upload_backend);
  907. bytes_read += read_iteration;
  908. ++buffer_idx;
  909. buffer_idx %= n_buffers;
  910. }
  911. } else {
  912. read_buf.resize(n_size);
  913. file->seek(weight->offs, SEEK_SET);
  914. file->read_raw(read_buf.data(), n_size);
  915. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  916. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  917. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  918. }
  919. }
  920. }
  921. }
  922. size_done += n_size;
  923. }
  924. // free temporary resources used for async uploads
  925. for (auto * event : events) {
  926. ggml_backend_event_synchronize(event);
  927. ggml_backend_event_free(event);
  928. }
  929. for (auto * buf : host_buffers) {
  930. ggml_backend_buffer_free(buf);
  931. }
  932. ggml_backend_free(upload_backend);
  933. // check validation results
  934. bool validation_failed = false;
  935. for (auto & future : validation_result) {
  936. auto result = future.get();
  937. if (!result.second) {
  938. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  939. validation_failed = true;
  940. }
  941. }
  942. if (validation_failed) {
  943. throw std::runtime_error("found tensors with invalid data");
  944. }
  945. // check if this is the last call and do final cleanup
  946. if (size_done >= size_data) {
  947. // unmap offloaded tensors and metadata
  948. if (use_mmap) {
  949. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  950. const auto & mmap_used = mmaps_used.at(idx);
  951. auto & mapping = mappings.at(idx);
  952. mapping->unmap_fragment(0, mmap_used.first);
  953. if (mmap_used.second != 0) {
  954. mapping->unmap_fragment(mmap_used.second, mapping->size());
  955. }
  956. }
  957. }
  958. if (progress_callback) {
  959. // Even though the model is done loading, we still honor
  960. // cancellation since we need to free allocations.
  961. return progress_callback(1.0f, progress_callback_user_data);
  962. }
  963. }
  964. return true;
  965. }
  966. std::string llama_model_loader::ftype_name() const {
  967. return llama_model_ftype_name(ftype);
  968. }
  969. void llama_model_loader::print_info() const {
  970. LLAMA_LOG_INFO("%s: file format = %s\n", __func__, llama_file_version_name(fver));
  971. LLAMA_LOG_INFO("%s: file type = %s\n", __func__, llama_model_ftype_name(ftype).c_str());
  972. if (n_bytes < GiB) {
  973. LLAMA_LOG_INFO("%s: file size = %.2f MiB (%.2f BPW) \n", __func__, n_bytes/1024.0/1024.0, n_bytes*8.0/n_elements);
  974. } else {
  975. LLAMA_LOG_INFO("%s: file size = %.2f GiB (%.2f BPW) \n", __func__, n_bytes/1024.0/1024.0/1024.0, n_bytes*8.0/n_elements);
  976. }
  977. }