ggml-backend-reg.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /**
  2. * llama.cpp - commit 081b29bd2a3d91e7772e3910ce223dd63b8d7d26 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "ggml-backend-impl.h"
  27. #include "ggml-backend.h"
  28. #include "ggml-impl.h"
  29. #include <algorithm>
  30. #include <codecvt>
  31. #include <cstring>
  32. #include <filesystem>
  33. #include <locale>
  34. #include <memory>
  35. #include <string>
  36. #include <type_traits>
  37. #include <vector>
  38. #ifdef _WIN32
  39. # define WIN32_LEAN_AND_MEAN
  40. # ifndef NOMINMAX
  41. # define NOMINMAX
  42. # endif
  43. # include <windows.h>
  44. #elif defined(__APPLE__)
  45. # include <mach-o/dyld.h>
  46. # include <dlfcn.h>
  47. #else
  48. # include <dlfcn.h>
  49. # include <unistd.h>
  50. #endif
  51. // Backend registry
  52. #ifdef GGML_USE_CPU
  53. #include "ggml-cpu.h"
  54. #endif
  55. #ifdef GGML_USE_CUDA
  56. #include "ggml-cuda.h"
  57. #endif
  58. #ifdef GGML_USE_METAL
  59. #include "ggml-metal.h"
  60. #endif
  61. #ifdef GGML_USE_SYCL
  62. #include "ggml-sycl.h"
  63. #endif
  64. #ifdef GGML_USE_VULKAN
  65. #include "ggml-vulkan.h"
  66. #endif
  67. #ifdef GGML_USE_OPENCL
  68. #include "ggml-opencl.h"
  69. #endif
  70. #ifdef GGML_USE_BLAS
  71. #include "ggml-blas.h"
  72. #endif
  73. #ifdef GGML_USE_RPC
  74. #include "ggml-rpc.h"
  75. #endif
  76. #ifdef GGML_USE_CANN
  77. #include "ggml-cann.h"
  78. #endif
  79. #ifdef GGML_USE_KOMPUTE
  80. #include "ggml-kompute.h"
  81. #endif
  82. #ifdef _WIN32
  83. using dl_handle = std::remove_pointer_t<HMODULE>;
  84. struct dl_handle_deleter {
  85. void operator()(HMODULE handle) {
  86. FreeLibrary(handle);
  87. }
  88. };
  89. static dl_handle * dl_load_library(const std::wstring & path) {
  90. // suppress error dialogs for missing DLLs
  91. DWORD old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
  92. SetErrorMode(old_mode | SEM_FAILCRITICALERRORS);
  93. HMODULE handle = LoadLibraryW(path.c_str());
  94. SetErrorMode(old_mode);
  95. return handle;
  96. }
  97. static dl_handle * dl_load_library(const std::string & path) {
  98. std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  99. return dl_load_library(converter.from_bytes(path));
  100. }
  101. static void * dl_get_sym(dl_handle * handle, const char * name) {
  102. DWORD old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
  103. SetErrorMode(old_mode | SEM_FAILCRITICALERRORS);
  104. void * p = (void *) GetProcAddress(handle, name);
  105. SetErrorMode(old_mode);
  106. return p;
  107. }
  108. #else
  109. using dl_handle = void;
  110. struct dl_handle_deleter {
  111. void operator()(void * handle) {
  112. dlclose(handle);
  113. }
  114. };
  115. static void * dl_load_library(const std::string & path) {
  116. dl_handle * handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
  117. return handle;
  118. }
  119. static void * dl_get_sym(dl_handle * handle, const char * name) {
  120. return dlsym(handle, name);
  121. }
  122. #endif
  123. using dl_handle_ptr = std::unique_ptr<dl_handle, dl_handle_deleter>;
  124. struct ggml_backend_reg_entry {
  125. ggml_backend_reg_t reg;
  126. dl_handle_ptr handle;
  127. };
  128. struct ggml_backend_registry {
  129. std::vector<ggml_backend_reg_entry> backends;
  130. std::vector<ggml_backend_dev_t> devices;
  131. ggml_backend_registry() {
  132. #ifdef GGML_USE_CUDA
  133. register_backend(ggml_backend_cuda_reg());
  134. #endif
  135. #ifdef GGML_USE_METAL
  136. register_backend(ggml_backend_metal_reg());
  137. #endif
  138. #ifdef GGML_USE_SYCL
  139. register_backend(ggml_backend_sycl_reg());
  140. #endif
  141. #ifdef GGML_USE_VULKAN
  142. register_backend(ggml_backend_vk_reg());
  143. #endif
  144. #ifdef GGML_USE_OPENCL
  145. register_backend(ggml_backend_opencl_reg());
  146. #endif
  147. #ifdef GGML_USE_CANN
  148. register_backend(ggml_backend_cann_reg());
  149. #endif
  150. #ifdef GGML_USE_BLAS
  151. register_backend(ggml_backend_blas_reg());
  152. #endif
  153. #ifdef GGML_USE_RPC
  154. register_backend(ggml_backend_rpc_reg());
  155. #endif
  156. #ifdef GGML_USE_KOMPUTE
  157. register_backend(ggml_backend_kompute_reg());
  158. #endif
  159. #ifdef GGML_USE_CPU
  160. register_backend(ggml_backend_cpu_reg());
  161. #endif
  162. }
  163. ~ggml_backend_registry() {
  164. // FIXME: backends cannot be safely unloaded without a function to destroy all the backend resources,
  165. // since backend threads may still be running and accessing resources from the dynamic library
  166. for (auto & entry : backends) {
  167. if (entry.handle) {
  168. entry.handle.release(); // NOLINT
  169. }
  170. }
  171. }
  172. void register_backend(ggml_backend_reg_t reg, dl_handle_ptr handle = nullptr) {
  173. if (!reg) {
  174. return;
  175. }
  176. #ifndef NDEBUG
  177. GGML_LOG_DEBUG("%s: registered backend %s (%zu devices)\n",
  178. __func__, ggml_backend_reg_name(reg), ggml_backend_reg_dev_count(reg));
  179. #endif
  180. backends.push_back({ reg, std::move(handle) });
  181. for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); i++) {
  182. register_device(ggml_backend_reg_dev_get(reg, i));
  183. }
  184. }
  185. void register_device(ggml_backend_dev_t device) {
  186. #ifndef NDEBUG
  187. GGML_LOG_DEBUG("%s: registered device %s (%s)\n", __func__, ggml_backend_dev_name(device), ggml_backend_dev_description(device));
  188. #endif
  189. devices.push_back(device);
  190. }
  191. ggml_backend_reg_t load_backend(const char * path, bool silent) {
  192. dl_handle_ptr handle { dl_load_library(path) };
  193. if (!handle) {
  194. if (!silent) {
  195. GGML_LOG_ERROR("%s: failed to load %s\n", __func__, path);
  196. }
  197. return nullptr;
  198. }
  199. auto score_fn = (ggml_backend_score_t) dl_get_sym(handle.get(), "ggml_backend_score");
  200. if (score_fn && score_fn() == 0) {
  201. if (!silent) {
  202. GGML_LOG_INFO("%s: backend %s is not supported on this system\n", __func__, path);
  203. }
  204. return nullptr;
  205. }
  206. auto backend_init_fn = (ggml_backend_init_t) dl_get_sym(handle.get(), "ggml_backend_init");
  207. if (!backend_init_fn) {
  208. if (!silent) {
  209. GGML_LOG_ERROR("%s: failed to find ggml_backend_init in %s\n", __func__, path);
  210. }
  211. return nullptr;
  212. }
  213. ggml_backend_reg_t reg = backend_init_fn();
  214. if (!reg || reg->api_version != GGML_BACKEND_API_VERSION) {
  215. if (!silent) {
  216. if (!reg) {
  217. GGML_LOG_ERROR("%s: failed to initialize backend from %s: ggml_backend_init returned NULL\n", __func__, path);
  218. } else {
  219. GGML_LOG_ERROR("%s: failed to initialize backend from %s: incompatible API version (backend: %d, current: %d)\n",
  220. __func__, path, reg->api_version, GGML_BACKEND_API_VERSION);
  221. }
  222. }
  223. return nullptr;
  224. }
  225. GGML_LOG_INFO("%s: loaded %s backend from %s\n", __func__, ggml_backend_reg_name(reg), path);
  226. register_backend(reg, std::move(handle));
  227. return reg;
  228. }
  229. void unload_backend(ggml_backend_reg_t reg, bool silent) {
  230. auto it = std::find_if(backends.begin(), backends.end(),
  231. [reg](const ggml_backend_reg_entry & entry) { return entry.reg == reg; });
  232. if (it == backends.end()) {
  233. if (!silent) {
  234. GGML_LOG_ERROR("%s: backend not found\n", __func__);
  235. }
  236. return;
  237. }
  238. if (!silent) {
  239. GGML_LOG_DEBUG("%s: unloading %s backend\n", __func__, ggml_backend_reg_name(reg));
  240. }
  241. // remove devices
  242. devices.erase(
  243. std::remove_if(devices.begin(), devices.end(),
  244. [reg](ggml_backend_dev_t dev) { return ggml_backend_dev_backend_reg(dev) == reg; }),
  245. devices.end());
  246. // remove backend
  247. backends.erase(it);
  248. }
  249. };
  250. static ggml_backend_registry & get_reg() {
  251. static ggml_backend_registry reg;
  252. return reg;
  253. }
  254. // Internal API
  255. void ggml_backend_register(ggml_backend_reg_t reg) {
  256. get_reg().register_backend(reg);
  257. }
  258. void ggml_backend_device_register(ggml_backend_dev_t device) {
  259. get_reg().register_device(device);
  260. }
  261. // Backend (reg) enumeration
  262. static bool striequals(const char * a, const char * b) {
  263. for (; *a && *b; a++, b++) {
  264. if (std::tolower(*a) != std::tolower(*b)) {
  265. return false;
  266. }
  267. }
  268. return *a == *b;
  269. }
  270. size_t ggml_backend_reg_count() {
  271. return get_reg().backends.size();
  272. }
  273. ggml_backend_reg_t ggml_backend_reg_get(size_t index) {
  274. GGML_ASSERT(index < ggml_backend_reg_count());
  275. return get_reg().backends[index].reg;
  276. }
  277. ggml_backend_reg_t ggml_backend_reg_by_name(const char * name) {
  278. for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
  279. ggml_backend_reg_t reg = ggml_backend_reg_get(i);
  280. if (striequals(ggml_backend_reg_name(reg), name)) {
  281. return reg;
  282. }
  283. }
  284. return nullptr;
  285. }
  286. // Device enumeration
  287. size_t ggml_backend_dev_count() {
  288. return get_reg().devices.size();
  289. }
  290. ggml_backend_dev_t ggml_backend_dev_get(size_t index) {
  291. GGML_ASSERT(index < ggml_backend_dev_count());
  292. return get_reg().devices[index];
  293. }
  294. ggml_backend_dev_t ggml_backend_dev_by_name(const char * name) {
  295. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  296. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  297. if (striequals(ggml_backend_dev_name(dev), name)) {
  298. return dev;
  299. }
  300. }
  301. return nullptr;
  302. }
  303. ggml_backend_dev_t ggml_backend_dev_by_type(enum ggml_backend_dev_type type) {
  304. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  305. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  306. if (ggml_backend_dev_type(dev) == type) {
  307. return dev;
  308. }
  309. }
  310. return nullptr;
  311. }
  312. // Convenience functions
  313. ggml_backend_t ggml_backend_init_by_name(const char * name, const char * params) {
  314. ggml_backend_dev_t dev = ggml_backend_dev_by_name(name);
  315. if (!dev) {
  316. return nullptr;
  317. }
  318. return ggml_backend_dev_init(dev, params);
  319. }
  320. ggml_backend_t ggml_backend_init_by_type(enum ggml_backend_dev_type type, const char * params) {
  321. ggml_backend_dev_t dev = ggml_backend_dev_by_type(type);
  322. if (!dev) {
  323. return nullptr;
  324. }
  325. return ggml_backend_dev_init(dev, params);
  326. }
  327. ggml_backend_t ggml_backend_init_best(void) {
  328. ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU);
  329. if (!dev) {
  330. dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  331. }
  332. if (!dev) {
  333. return nullptr;
  334. }
  335. return ggml_backend_dev_init(dev, nullptr);
  336. }
  337. // Dynamic loading
  338. ggml_backend_reg_t ggml_backend_load(const char * path) {
  339. return get_reg().load_backend(path, false);
  340. }
  341. void ggml_backend_unload(ggml_backend_reg_t reg) {
  342. get_reg().unload_backend(reg, true);
  343. }
  344. static std::string get_executable_path() {
  345. #if defined(__APPLE__)
  346. // get executable path
  347. std::vector<char> path;
  348. uint32_t size;
  349. while (true) {
  350. size = path.size();
  351. if (_NSGetExecutablePath(path.data(), &size) == 0) {
  352. break;
  353. }
  354. path.resize(size);
  355. }
  356. std::string base_path(path.data(), size);
  357. // remove executable name
  358. auto last_slash = base_path.find_last_of('/');
  359. if (last_slash != std::string::npos) {
  360. base_path = base_path.substr(0, last_slash);
  361. }
  362. return base_path + "/";
  363. #elif defined(__linux__)
  364. std::string base_path = ".";
  365. std::vector<char> path(1024);
  366. while (true) {
  367. // get executable path
  368. ssize_t len = readlink("/proc/self/exe", path.data(), path.size());
  369. if (len == -1) {
  370. break;
  371. }
  372. if (len < (ssize_t) path.size()) {
  373. base_path = std::string(path.data(), len);
  374. // remove executable name
  375. auto last_slash = base_path.find_last_of('/');
  376. if (last_slash != std::string::npos) {
  377. base_path = base_path.substr(0, last_slash);
  378. }
  379. break;
  380. }
  381. path.resize(path.size() * 2);
  382. }
  383. return base_path + "/";
  384. #elif defined(_WIN32)
  385. std::vector<char> path(MAX_PATH);
  386. DWORD len = GetModuleFileNameA(NULL, path.data(), path.size());
  387. if (len == 0) {
  388. return "";
  389. }
  390. std::string base_path(path.data(), len);
  391. // remove executable name
  392. auto last_slash = base_path.find_last_of('\\');
  393. if (last_slash != std::string::npos) {
  394. base_path = base_path.substr(0, last_slash);
  395. }
  396. return base_path + "\\";
  397. #endif
  398. }
  399. static std::string backend_filename_prefix() {
  400. #ifdef _WIN32
  401. return "ggml-";
  402. #else
  403. return "libggml-";
  404. #endif
  405. }
  406. static std::string backend_filename_suffix() {
  407. #ifdef _WIN32
  408. return ".dll";
  409. #else
  410. return ".so";
  411. #endif
  412. }
  413. static ggml_backend_reg_t ggml_backend_load_best(const char * name, bool silent, const char * user_search_path) {
  414. // enumerate all the files that match [lib]ggml-name-*.[so|dll] in the search paths
  415. // TODO: search system paths
  416. std::string file_prefix = backend_filename_prefix() + name + "-";
  417. std::vector<std::string> search_paths;
  418. if (user_search_path == nullptr) {
  419. search_paths.push_back("./");
  420. search_paths.push_back(get_executable_path());
  421. } else {
  422. #if defined(_WIN32)
  423. search_paths.push_back(std::string(user_search_path) + "\\");
  424. #else
  425. search_paths.push_back(std::string(user_search_path) + "/");
  426. #endif
  427. }
  428. int best_score = 0;
  429. std::string best_path;
  430. namespace fs = std::filesystem;
  431. for (const auto & search_path : search_paths) {
  432. if (!fs::exists(search_path)) {
  433. continue;
  434. }
  435. fs::directory_iterator dir_it(search_path, fs::directory_options::skip_permission_denied);
  436. for (const auto & entry : dir_it) {
  437. if (entry.is_regular_file()) {
  438. std::string filename = entry.path().filename().string();
  439. std::string ext = entry.path().extension().string();
  440. if (filename.find(file_prefix) == 0 && ext == backend_filename_suffix()) {
  441. dl_handle_ptr handle { dl_load_library(entry.path().c_str()) };
  442. if (!handle && !silent) {
  443. GGML_LOG_ERROR("%s: failed to load %s\n", __func__, entry.path().string().c_str());
  444. }
  445. if (handle) {
  446. auto score_fn = (ggml_backend_score_t) dl_get_sym(handle.get(), "ggml_backend_score");
  447. if (score_fn) {
  448. int s = score_fn();
  449. #ifndef NDEBUG
  450. GGML_LOG_DEBUG("%s: %s score: %d\n", __func__, entry.path().string().c_str(), s);
  451. #endif
  452. if (s > best_score) {
  453. best_score = s;
  454. best_path = entry.path().string();
  455. }
  456. } else {
  457. if (!silent) {
  458. GGML_LOG_INFO("%s: failed to find ggml_backend_score in %s\n", __func__, entry.path().string().c_str());
  459. }
  460. }
  461. }
  462. }
  463. }
  464. }
  465. }
  466. if (best_score == 0) {
  467. // try to load the base backend
  468. for (const auto & search_path : search_paths) {
  469. std::string path = search_path + backend_filename_prefix() + name + backend_filename_suffix();
  470. if (fs::exists(path)) {
  471. return get_reg().load_backend(path.c_str(), silent);
  472. }
  473. }
  474. return nullptr;
  475. }
  476. return get_reg().load_backend(best_path.c_str(), silent);
  477. }
  478. void ggml_backend_load_all() {
  479. ggml_backend_load_all_from_path(nullptr);
  480. }
  481. void ggml_backend_load_all_from_path(const char * dir_path) {
  482. #ifdef NDEBUG
  483. bool silent = true;
  484. #else
  485. bool silent = false;
  486. #endif
  487. ggml_backend_load_best("blas", silent, dir_path);
  488. ggml_backend_load_best("cann", silent, dir_path);
  489. ggml_backend_load_best("cuda", silent, dir_path);
  490. ggml_backend_load_best("hip", silent, dir_path);
  491. ggml_backend_load_best("kompute", silent, dir_path);
  492. ggml_backend_load_best("metal", silent, dir_path);
  493. ggml_backend_load_best("rpc", silent, dir_path);
  494. ggml_backend_load_best("sycl", silent, dir_path);
  495. ggml_backend_load_best("vulkan", silent, dir_path);
  496. ggml_backend_load_best("opencl", silent, dir_path);
  497. ggml_backend_load_best("musa", silent, dir_path);
  498. ggml_backend_load_best("cpu", silent, dir_path);
  499. }