llama-model-loader.cpp 45 KB

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