llama-model-loader.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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_UINT32:
  261. case GGUF_TYPE_INT32: GGML_ASSERT((std::is_same<T, int32_t>::value) ||
  262. (std::is_same<T, uint32_t>::value)); break;
  263. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  264. default:
  265. throw std::runtime_error(format("%s is not a float32/uint32/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_UINT32:
  284. case GGUF_TYPE_INT32: GGML_ASSERT((std::is_same<T, int32_t>::value) ||
  285. (std::is_same<T, uint32_t>::value)); break;
  286. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  287. default:
  288. throw std::runtime_error(format("%s is not a float32/uint32/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 llama_model_kv_override * param_overrides_p,
  374. const llama_model_tensor_buft_override * param_tensor_buft_overrides_p) {
  375. int trace = 0;
  376. if (getenv("LLAMA_TRACE")) {
  377. trace = atoi(getenv("LLAMA_TRACE"));
  378. }
  379. if (param_overrides_p != nullptr) {
  380. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  381. kv_overrides.insert({std::string(p->key), *p});
  382. }
  383. }
  384. tensor_buft_overrides = param_tensor_buft_overrides_p;
  385. // Load the main GGUF
  386. struct ggml_context * ctx = NULL;
  387. struct gguf_init_params params = {
  388. /*.no_alloc = */ true,
  389. /*.ctx = */ &ctx,
  390. };
  391. meta.reset(gguf_init_from_file(fname.c_str(), params));
  392. if (!meta) {
  393. throw std::runtime_error(format("%s: failed to load model from %s", __func__, fname.c_str()));
  394. }
  395. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  396. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  397. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  398. contexts.emplace_back(ctx);
  399. // Save tensors data offset of the main file.
  400. // For subsidiary files, `meta` tensor data offset must not be used,
  401. // so we build a unified tensors index for weights.
  402. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  403. std::string tensor_name = std::string(cur->name);
  404. // make sure there is no duplicated tensor names
  405. if (weights_map.find(tensor_name) != weights_map.end()) {
  406. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  407. }
  408. n_elements += ggml_nelements(cur);
  409. n_bytes += ggml_nbytes(cur);
  410. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, meta.get(), cur));
  411. }
  412. uint16_t n_split = 0;
  413. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  414. // Load additional GGML contexts
  415. if (n_split > 1) {
  416. // make sure the main file is loaded first
  417. uint16_t idx = 0;
  418. const std::string kv_split_no = llm_kv(LLM_KV_SPLIT_NO);
  419. get_key(kv_split_no, idx);
  420. if (idx != 0) {
  421. throw std::runtime_error(format("illegal split file idx: %d (file: %s), model must be loaded with the first split", idx, fname.c_str()));
  422. }
  423. // generate list of splits if needed
  424. if (splits.empty()) {
  425. splits = llama_get_list_splits(fname, idx, n_split);
  426. }
  427. // in case user give a custom list of splits, check if it matches the expected number
  428. if (n_split != (uint16_t)splits.size()) {
  429. throw std::runtime_error(format("invalid split count, given: %zu splits, but expected %d", splits.size(), n_split));
  430. }
  431. if (trace > 0) {
  432. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  433. }
  434. // load other splits
  435. for (idx = 1; idx < n_split; idx++) {
  436. const char * fname_split = splits[idx].c_str();
  437. struct gguf_init_params split_params = {
  438. /*.no_alloc = */ true,
  439. /*.ctx = */ &ctx,
  440. };
  441. gguf_context_ptr ctx_gguf { gguf_init_from_file(fname_split, split_params) };
  442. if (!ctx_gguf) {
  443. throw std::runtime_error(format("%s: failed to load GGUF split from %s", __func__, fname_split));
  444. }
  445. // check idx
  446. {
  447. const int kid = gguf_find_key(ctx_gguf.get(), kv_split_no.c_str());
  448. if (kid < 0) {
  449. throw std::runtime_error(format("missing key %s in GGUF split %s", kv_split_no.c_str(), fname_split));
  450. }
  451. int idx_gguf = gguf_get_val_u16(ctx_gguf.get(), kid);
  452. if (idx_gguf != idx) {
  453. throw std::runtime_error(format("invalid split file idx: %d (file: %s), expected %d", idx_gguf, fname_split, idx));
  454. }
  455. }
  456. files.emplace_back(new llama_file(fname_split, "rb"));
  457. contexts.emplace_back(ctx);
  458. // Save tensors data offset info of the shard.
  459. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  460. std::string tensor_name = std::string(cur->name);
  461. // make sure there is no duplicated tensor names
  462. if (weights_map.find(tensor_name) != weights_map.end()) {
  463. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  464. }
  465. n_elements += ggml_nelements(cur);
  466. n_bytes += ggml_nbytes(cur);
  467. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), idx, ctx_gguf.get(), cur));
  468. }
  469. }
  470. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  471. // sanity check
  472. {
  473. const int n_tensors_loaded = (int) weights_map.size();
  474. if (n_tensors != n_tensors_loaded) {
  475. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  476. }
  477. }
  478. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  479. }
  480. n_kv = gguf_get_n_kv(meta.get());
  481. n_tensors = weights_map.size();
  482. fver = (enum llama_fver) gguf_get_version(meta.get());
  483. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  484. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  485. // determine file type based on the number of tensors for each quantization and print meta data
  486. // TODO: make optional
  487. {
  488. std::map<enum ggml_type, uint32_t> n_type;
  489. uint32_t n_type_max = 0;
  490. enum ggml_type type_max = GGML_TYPE_F32;
  491. for (const auto & it : weights_map) {
  492. const llama_tensor_weight & w = it.second;
  493. const ggml_tensor * tensor = w.tensor;
  494. enum ggml_type type = tensor->type;
  495. n_type[type]++;
  496. if (n_type_max < n_type[type]) {
  497. n_type_max = n_type[type];
  498. type_max = type;
  499. }
  500. if (trace > 0) {
  501. const uint16_t sid = w.idx;
  502. LLAMA_LOG_INFO("%s: - tensor split %2d: %32s %-8s [ %s ] %8.2f MiB\n", __func__,
  503. sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str(),
  504. ggml_nbytes(tensor)/1024.0f/1024.0f);
  505. }
  506. }
  507. switch (type_max) {
  508. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  509. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  510. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  511. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  512. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  513. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  514. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  515. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  516. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  517. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  518. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  519. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  520. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  521. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  522. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  523. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  524. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  525. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  526. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  527. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  528. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  529. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  530. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  531. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  532. default:
  533. {
  534. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  535. ftype = LLAMA_FTYPE_ALL_F32;
  536. } break;
  537. }
  538. // this is a way to mark that we have "guessed" the file type
  539. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  540. {
  541. uint32_t ftype_val = 0;
  542. if (get_key(LLM_KV_GENERAL_FILE_TYPE, ftype_val, false)) {
  543. ftype = (llama_ftype) ftype_val;
  544. }
  545. }
  546. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  547. for (int i = 0; i < n_kv; i++) {
  548. const char * name = gguf_get_key(meta.get(), i);
  549. const enum gguf_type type = gguf_get_kv_type(meta.get(), i);
  550. const std::string type_name =
  551. type == GGUF_TYPE_ARRAY
  552. ? 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))
  553. : gguf_type_name(type);
  554. std::string value = gguf_kv_to_str(meta.get(), i);
  555. const size_t MAX_VALUE_LEN = 40;
  556. if (value.size() > MAX_VALUE_LEN) {
  557. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  558. }
  559. replace_all(value, "\n", "\\n");
  560. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  561. }
  562. // print type counts
  563. for (auto & kv : n_type) {
  564. if (kv.second == 0) {
  565. continue;
  566. }
  567. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  568. }
  569. }
  570. if (!llama_mmap::SUPPORTED) {
  571. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  572. use_mmap = false;
  573. }
  574. this->use_mmap = use_mmap;
  575. this->check_tensors = check_tensors;
  576. }
  577. std::string llama_model_loader::get_arch_name() const {
  578. return arch_name;
  579. }
  580. enum llm_arch llama_model_loader::get_arch() const {
  581. return llm_kv.arch;
  582. }
  583. const llama_model_loader::llama_tensor_weight * llama_model_loader::get_weight(const char * name) const {
  584. auto pos = weights_map.find(name);
  585. if (pos != weights_map.end()) {
  586. return &pos->second;
  587. }
  588. return nullptr;
  589. }
  590. const llama_model_loader::llama_tensor_weight & llama_model_loader::require_weight(const char * name) const {
  591. const llama_tensor_weight * weight = get_weight(name);
  592. if (!weight) {
  593. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  594. }
  595. return *weight;
  596. }
  597. struct ggml_tensor * llama_model_loader::get_tensor_meta(const char * name) const {
  598. const auto * weight = get_weight(name);
  599. if (!weight) {
  600. return nullptr;
  601. }
  602. return weight->tensor;
  603. }
  604. struct ggml_tensor * llama_model_loader::require_tensor_meta(const std::string & name) const {
  605. struct ggml_tensor * tensor = get_tensor_meta(name.c_str());
  606. if (!tensor) {
  607. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  608. }
  609. return tensor;
  610. }
  611. const struct ggml_tensor * llama_model_loader::check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  612. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  613. if (cur == NULL) {
  614. if (!required) {
  615. return NULL;
  616. }
  617. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  618. }
  619. {
  620. bool is_ok = true;
  621. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  622. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  623. is_ok = false;
  624. break;
  625. }
  626. }
  627. if (!is_ok) {
  628. throw std::runtime_error(
  629. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  630. __func__, name.c_str(),
  631. llama_format_tensor_shape(ne).c_str(),
  632. llama_format_tensor_shape(cur).c_str()));
  633. }
  634. }
  635. return cur;
  636. }
  637. 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) {
  638. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  639. if (cur == NULL) {
  640. return NULL;
  641. }
  642. bool duplicated = flags & TENSOR_DUPLICATED;
  643. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  644. ggml_set_name(tensor, ggml_get_name(cur));
  645. if (duplicated) {
  646. size_data += ggml_nbytes(cur);
  647. } else {
  648. n_created++;
  649. }
  650. return tensor;
  651. }
  652. 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) {
  653. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  654. if (cur == NULL) {
  655. return NULL;
  656. }
  657. if (cur->type != base->type) {
  658. 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)));
  659. }
  660. std::array<int64_t, GGML_MAX_DIMS> dims;
  661. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  662. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  663. }
  664. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  665. dims[0], dims[1], dims[2], dims[3],
  666. cur->nb[1], cur->nb[2], cur->nb[3],
  667. offset);
  668. ggml_set_name(tensor, name.c_str());
  669. n_created++;
  670. return tensor;
  671. }
  672. void llama_model_loader::done_getting_tensors() const {
  673. if (n_created != n_tensors) {
  674. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  675. }
  676. }
  677. void llama_model_loader::init_mappings(bool prefetch, llama_mlocks * mlock_mmaps) {
  678. if (use_mmap) {
  679. mappings.reserve(files.size());
  680. mmaps_used.reserve(files.size());
  681. for (const auto & file : files) {
  682. bool is_numa = false;
  683. auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  684. if (dev) {
  685. auto * reg = ggml_backend_dev_backend_reg(dev);
  686. auto * is_numa_fn = (decltype(ggml_is_numa) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_is_numa");
  687. if (is_numa_fn) {
  688. is_numa = is_numa_fn();
  689. }
  690. }
  691. std::unique_ptr<llama_mmap> mapping = std::make_unique<llama_mmap>(file.get(), prefetch ? -1 : 0, is_numa);
  692. mmaps_used.emplace_back(mapping->size(), 0);
  693. if (mlock_mmaps) {
  694. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  695. mlock_mmap->init(mapping->addr());
  696. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  697. }
  698. mappings.emplace_back(std::move(mapping));
  699. }
  700. }
  701. // compute the total size of all tensors for progress reporting
  702. for (const auto & it : weights_map) {
  703. size_data += ggml_nbytes(it.second.tensor);
  704. }
  705. }
  706. void llama_model_loader::get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  707. GGML_ASSERT(!mappings.empty());
  708. const auto & mapping = mappings.at(idx);
  709. *first = mapping->size();
  710. *last = 0;
  711. *addr = mapping->addr();
  712. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  713. const auto * weight = get_weight(ggml_get_name(tensor));
  714. if (!weight || weight->idx != idx) {
  715. continue;
  716. }
  717. *first = std::min(*first, weight->offs);
  718. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  719. }
  720. }
  721. void llama_model_loader::load_data_for(struct ggml_tensor * cur) const {
  722. const auto & w = require_weight(ggml_get_name(cur));
  723. if (use_mmap) {
  724. const auto & mapping = mappings.at(w.idx);
  725. if (cur->data == nullptr) {
  726. cur->data = (uint8_t *)mapping->addr() + w.offs;
  727. } else {
  728. memcpy(cur->data, (uint8_t *)mapping->addr() + w.offs, ggml_nbytes(cur));
  729. }
  730. } else {
  731. GGML_ASSERT(cur->data != nullptr);
  732. GGML_ASSERT(w.idx < files.size());
  733. const auto & file = files.at(w.idx);
  734. file->seek(w.offs, SEEK_SET);
  735. file->read_raw(cur->data, ggml_nbytes(cur));
  736. }
  737. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  738. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  739. }
  740. }
  741. bool llama_model_loader::load_all_data(
  742. struct ggml_context * ctx,
  743. llama_buf_map & bufs,
  744. llama_mlocks * lmlocks,
  745. llama_progress_callback progress_callback,
  746. void * progress_callback_user_data) {
  747. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  748. std::vector<no_init<uint8_t>> read_buf;
  749. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  750. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  751. // NVMe raid configurations might require more / larger buffers.
  752. constexpr size_t n_buffers = 4;
  753. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  754. std::vector<ggml_backend_buffer_t> host_buffers;
  755. std::vector<ggml_backend_event_t> events;
  756. std::vector<void *> host_ptrs;
  757. size_t buffer_idx = 0; // buffer to use for async loads
  758. ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t {
  759. if (use_mmap || check_tensors) {
  760. return nullptr;
  761. }
  762. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  763. // First determine if the backend supports the necessary features for async uploads.
  764. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  765. if (!buf) {
  766. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func);
  767. return nullptr;
  768. }
  769. auto * buft = ggml_backend_buffer_get_type(buf);
  770. auto * dev = ggml_backend_buft_get_device(buft);
  771. if (!dev) {
  772. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func,
  773. ggml_backend_buft_name(buft));
  774. return nullptr;
  775. }
  776. if (buft != ggml_backend_dev_buffer_type(dev)) {
  777. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func,
  778. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  779. return nullptr;
  780. }
  781. ggml_backend_dev_props props;
  782. ggml_backend_dev_get_props(dev, &props);
  783. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  784. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func,
  785. ggml_backend_dev_name(dev));
  786. return nullptr;
  787. }
  788. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  789. if (!host_buft) {
  790. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func,
  791. ggml_backend_dev_name(dev));
  792. return nullptr;
  793. }
  794. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  795. for (size_t idx = 0; idx < n_buffers; ++idx) {
  796. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  797. if (!buf) {
  798. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", func,
  799. ggml_backend_dev_name(dev));
  800. return nullptr;
  801. }
  802. host_buffers.emplace_back(buf);
  803. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  804. auto * event = ggml_backend_event_new(dev);
  805. if (!event) {
  806. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", func,
  807. ggml_backend_dev_name(dev));
  808. return nullptr;
  809. }
  810. events.emplace_back(event);
  811. }
  812. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  813. if (!backend) {
  814. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", func,
  815. ggml_backend_dev_name(dev));
  816. return nullptr;
  817. }
  818. return backend;
  819. }(__func__);
  820. if (upload_backend) {
  821. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  822. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  823. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  824. ggml_backend_name(upload_backend));
  825. }
  826. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  827. const auto * weight = get_weight(ggml_get_name(cur));
  828. if (weight == nullptr) {
  829. // this can happen with split experts models
  830. continue;
  831. }
  832. if (progress_callback) {
  833. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  834. return false;
  835. }
  836. }
  837. size_t n_size = ggml_nbytes(cur);
  838. if (use_mmap) {
  839. const auto & mapping = mappings.at(weight->idx);
  840. ggml_backend_buffer_t buf_mmap = nullptr;
  841. if (bufs.count(weight->idx)) {
  842. buf_mmap = bufs.at(weight->idx);
  843. }
  844. uint8_t * data = (uint8_t *) mapping->addr() + weight->offs;
  845. if (check_tensors) {
  846. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  847. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  848. }));
  849. }
  850. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  851. if (buf_mmap && cur->data == nullptr) {
  852. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  853. if (lmlocks) {
  854. const auto & lmlock = lmlocks->at(weight->idx);
  855. lmlock->grow_to(weight->offs + n_size);
  856. }
  857. auto & mmap_used = mmaps_used[weight->idx];
  858. mmap_used.first = std::min(mmap_used.first, weight->offs);
  859. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  860. } else {
  861. ggml_backend_tensor_set(cur, data, 0, n_size);
  862. }
  863. } else {
  864. const auto & file = files.at(weight->idx);
  865. if (ggml_backend_buffer_is_host(cur->buffer)) {
  866. file->seek(weight->offs, SEEK_SET);
  867. file->read_raw(cur->data, n_size);
  868. if (check_tensors) {
  869. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  870. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  871. }));
  872. }
  873. } else {
  874. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  875. if (upload_backend) {
  876. file->seek(weight->offs, SEEK_SET);
  877. size_t bytes_read = 0;
  878. while (bytes_read < n_size) {
  879. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  880. ggml_backend_event_synchronize(events[buffer_idx]);
  881. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  882. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  883. ggml_backend_event_record(events[buffer_idx], upload_backend);
  884. bytes_read += read_iteration;
  885. ++buffer_idx;
  886. buffer_idx %= n_buffers;
  887. }
  888. } else {
  889. read_buf.resize(n_size);
  890. file->seek(weight->offs, SEEK_SET);
  891. file->read_raw(read_buf.data(), n_size);
  892. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  893. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  894. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  895. }
  896. }
  897. }
  898. }
  899. size_done += n_size;
  900. }
  901. // free temporary resources used for async uploads
  902. for (auto * event : events) {
  903. ggml_backend_event_synchronize(event);
  904. ggml_backend_event_free(event);
  905. }
  906. for (auto * buf : host_buffers) {
  907. ggml_backend_buffer_free(buf);
  908. }
  909. ggml_backend_free(upload_backend);
  910. // check validation results
  911. bool validation_failed = false;
  912. for (auto & future : validation_result) {
  913. auto result = future.get();
  914. if (!result.second) {
  915. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  916. validation_failed = true;
  917. }
  918. }
  919. if (validation_failed) {
  920. throw std::runtime_error("found tensors with invalid data");
  921. }
  922. // check if this is the last call and do final cleanup
  923. if (size_done >= size_data) {
  924. // unmap offloaded tensors and metadata
  925. if (use_mmap) {
  926. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  927. const auto & mmap_used = mmaps_used.at(idx);
  928. auto & mapping = mappings.at(idx);
  929. mapping->unmap_fragment(0, mmap_used.first);
  930. if (mmap_used.second != 0) {
  931. mapping->unmap_fragment(mmap_used.second, mapping->size());
  932. }
  933. }
  934. }
  935. if (progress_callback) {
  936. // Even though the model is done loading, we still honor
  937. // cancellation since we need to free allocations.
  938. return progress_callback(1.0f, progress_callback_user_data);
  939. }
  940. }
  941. return true;
  942. }
  943. std::string llama_model_loader::ftype_name() const {
  944. return llama_model_ftype_name(ftype);
  945. }
  946. void llama_model_loader::print_info() const {
  947. LLAMA_LOG_INFO("%s: file format = %s\n", __func__, llama_file_version_name(fver));
  948. LLAMA_LOG_INFO("%s: file type = %s\n", __func__, llama_model_ftype_name(ftype).c_str());
  949. if (n_bytes < GiB) {
  950. LLAMA_LOG_INFO("%s: file size = %.2f MiB (%.2f BPW) \n", __func__, n_bytes/1024.0/1024.0, n_bytes*8.0/n_elements);
  951. } else {
  952. 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);
  953. }
  954. }