ggml-backend-reg.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /**
  2. * llama.cpp - commit 46e3556e01b824e52395fb050b29804b6cff2a7c - 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. // disable C++17 deprecation warning for std::codecvt_utf8
  83. #if defined(__clang__)
  84. # pragma clang diagnostic push
  85. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  86. #endif
  87. static std::wstring utf8_to_utf16(const std::string & str) {
  88. std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  89. return converter.from_bytes(str);
  90. }
  91. static std::string utf16_to_utf8(const std::wstring & str) {
  92. std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  93. return converter.to_bytes(str);
  94. }
  95. #if defined(__clang__)
  96. # pragma clang diagnostic pop
  97. #endif
  98. #ifdef _WIN32
  99. using dl_handle = std::remove_pointer_t<HMODULE>;
  100. struct dl_handle_deleter {
  101. void operator()(HMODULE handle) {
  102. FreeLibrary(handle);
  103. }
  104. };
  105. static dl_handle * dl_load_library(const std::wstring & path) {
  106. // suppress error dialogs for missing DLLs
  107. DWORD old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
  108. SetErrorMode(old_mode | SEM_FAILCRITICALERRORS);
  109. HMODULE handle = LoadLibraryW(path.c_str());
  110. SetErrorMode(old_mode);
  111. return handle;
  112. }
  113. static void * dl_get_sym(dl_handle * handle, const char * name) {
  114. DWORD old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
  115. SetErrorMode(old_mode | SEM_FAILCRITICALERRORS);
  116. void * p = (void *) GetProcAddress(handle, name);
  117. SetErrorMode(old_mode);
  118. return p;
  119. }
  120. #else
  121. using dl_handle = void;
  122. struct dl_handle_deleter {
  123. void operator()(void * handle) {
  124. dlclose(handle);
  125. }
  126. };
  127. static void * dl_load_library(const std::wstring & path) {
  128. dl_handle * handle = dlopen(utf16_to_utf8(path).c_str(), RTLD_NOW | RTLD_LOCAL);
  129. return handle;
  130. }
  131. static void * dl_get_sym(dl_handle * handle, const char * name) {
  132. return dlsym(handle, name);
  133. }
  134. #endif
  135. using dl_handle_ptr = std::unique_ptr<dl_handle, dl_handle_deleter>;
  136. struct ggml_backend_reg_entry {
  137. ggml_backend_reg_t reg;
  138. dl_handle_ptr handle;
  139. };
  140. struct ggml_backend_registry {
  141. std::vector<ggml_backend_reg_entry> backends;
  142. std::vector<ggml_backend_dev_t> devices;
  143. ggml_backend_registry() {
  144. #ifdef GGML_USE_CUDA
  145. register_backend(ggml_backend_cuda_reg());
  146. #endif
  147. #ifdef GGML_USE_METAL
  148. register_backend(ggml_backend_metal_reg());
  149. #endif
  150. #ifdef GGML_USE_SYCL
  151. register_backend(ggml_backend_sycl_reg());
  152. #endif
  153. #ifdef GGML_USE_VULKAN
  154. register_backend(ggml_backend_vk_reg());
  155. #endif
  156. #ifdef GGML_USE_OPENCL
  157. register_backend(ggml_backend_opencl_reg());
  158. #endif
  159. #ifdef GGML_USE_CANN
  160. register_backend(ggml_backend_cann_reg());
  161. #endif
  162. // #ifdef GGML_USE_BLAS
  163. // register_backend(ggml_backend_blas_reg());
  164. // #endif
  165. #ifdef GGML_USE_RPC
  166. register_backend(ggml_backend_rpc_reg());
  167. #endif
  168. #ifdef GGML_USE_KOMPUTE
  169. register_backend(ggml_backend_kompute_reg());
  170. #endif
  171. #ifdef GGML_USE_CPU
  172. register_backend(ggml_backend_cpu_reg());
  173. #endif
  174. }
  175. ~ggml_backend_registry() {
  176. // FIXME: backends cannot be safely unloaded without a function to destroy all the backend resources,
  177. // since backend threads may still be running and accessing resources from the dynamic library
  178. for (auto & entry : backends) {
  179. if (entry.handle) {
  180. entry.handle.release(); // NOLINT
  181. }
  182. }
  183. }
  184. void register_backend(ggml_backend_reg_t reg, dl_handle_ptr handle = nullptr) {
  185. if (!reg) {
  186. return;
  187. }
  188. #ifndef NDEBUG
  189. GGML_LOG_DEBUG("%s: registered backend %s (%zu devices)\n",
  190. __func__, ggml_backend_reg_name(reg), ggml_backend_reg_dev_count(reg));
  191. #endif
  192. backends.push_back({ reg, std::move(handle) });
  193. for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); i++) {
  194. register_device(ggml_backend_reg_dev_get(reg, i));
  195. }
  196. }
  197. void register_device(ggml_backend_dev_t device) {
  198. #ifndef NDEBUG
  199. GGML_LOG_DEBUG("%s: registered device %s (%s)\n", __func__, ggml_backend_dev_name(device), ggml_backend_dev_description(device));
  200. #endif
  201. devices.push_back(device);
  202. }
  203. ggml_backend_reg_t load_backend(const std::wstring & path, bool silent) {
  204. dl_handle_ptr handle { dl_load_library(path) };
  205. if (!handle) {
  206. if (!silent) {
  207. GGML_LOG_ERROR("%s: failed to load %s\n", __func__, utf16_to_utf8(path).c_str());
  208. }
  209. return nullptr;
  210. }
  211. auto score_fn = (ggml_backend_score_t) dl_get_sym(handle.get(), "ggml_backend_score");
  212. if (score_fn && score_fn() == 0) {
  213. if (!silent) {
  214. GGML_LOG_INFO("%s: backend %s is not supported on this system\n", __func__, utf16_to_utf8(path).c_str());
  215. }
  216. return nullptr;
  217. }
  218. auto backend_init_fn = (ggml_backend_init_t) dl_get_sym(handle.get(), "ggml_backend_init");
  219. if (!backend_init_fn) {
  220. if (!silent) {
  221. GGML_LOG_ERROR("%s: failed to find ggml_backend_init in %s\n", __func__, utf16_to_utf8(path).c_str());
  222. }
  223. return nullptr;
  224. }
  225. ggml_backend_reg_t reg = backend_init_fn();
  226. if (!reg || reg->api_version != GGML_BACKEND_API_VERSION) {
  227. if (!silent) {
  228. if (!reg) {
  229. GGML_LOG_ERROR("%s: failed to initialize backend from %s: ggml_backend_init returned NULL\n", __func__, utf16_to_utf8(path).c_str());
  230. } else {
  231. GGML_LOG_ERROR("%s: failed to initialize backend from %s: incompatible API version (backend: %d, current: %d)\n",
  232. __func__, utf16_to_utf8(path).c_str(), reg->api_version, GGML_BACKEND_API_VERSION);
  233. }
  234. }
  235. return nullptr;
  236. }
  237. GGML_LOG_INFO("%s: loaded %s backend from %s\n", __func__, ggml_backend_reg_name(reg), utf16_to_utf8(path).c_str());
  238. register_backend(reg, std::move(handle));
  239. return reg;
  240. }
  241. void unload_backend(ggml_backend_reg_t reg, bool silent) {
  242. auto it = std::find_if(backends.begin(), backends.end(),
  243. [reg](const ggml_backend_reg_entry & entry) { return entry.reg == reg; });
  244. if (it == backends.end()) {
  245. if (!silent) {
  246. GGML_LOG_ERROR("%s: backend not found\n", __func__);
  247. }
  248. return;
  249. }
  250. if (!silent) {
  251. GGML_LOG_DEBUG("%s: unloading %s backend\n", __func__, ggml_backend_reg_name(reg));
  252. }
  253. // remove devices
  254. devices.erase(
  255. std::remove_if(devices.begin(), devices.end(),
  256. [reg](ggml_backend_dev_t dev) { return ggml_backend_dev_backend_reg(dev) == reg; }),
  257. devices.end());
  258. // remove backend
  259. backends.erase(it);
  260. }
  261. };
  262. static ggml_backend_registry & get_reg() {
  263. static ggml_backend_registry reg;
  264. return reg;
  265. }
  266. // Internal API
  267. void ggml_backend_register(ggml_backend_reg_t reg) {
  268. get_reg().register_backend(reg);
  269. }
  270. void ggml_backend_device_register(ggml_backend_dev_t device) {
  271. get_reg().register_device(device);
  272. }
  273. // Backend (reg) enumeration
  274. static bool striequals(const char * a, const char * b) {
  275. for (; *a && *b; a++, b++) {
  276. if (std::tolower(*a) != std::tolower(*b)) {
  277. return false;
  278. }
  279. }
  280. return *a == *b;
  281. }
  282. size_t ggml_backend_reg_count() {
  283. return get_reg().backends.size();
  284. }
  285. ggml_backend_reg_t ggml_backend_reg_get(size_t index) {
  286. GGML_ASSERT(index < ggml_backend_reg_count());
  287. return get_reg().backends[index].reg;
  288. }
  289. ggml_backend_reg_t ggml_backend_reg_by_name(const char * name) {
  290. for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
  291. ggml_backend_reg_t reg = ggml_backend_reg_get(i);
  292. if (striequals(ggml_backend_reg_name(reg), name)) {
  293. return reg;
  294. }
  295. }
  296. return nullptr;
  297. }
  298. // Device enumeration
  299. size_t ggml_backend_dev_count() {
  300. return get_reg().devices.size();
  301. }
  302. ggml_backend_dev_t ggml_backend_dev_get(size_t index) {
  303. GGML_ASSERT(index < ggml_backend_dev_count());
  304. return get_reg().devices[index];
  305. }
  306. ggml_backend_dev_t ggml_backend_dev_by_name(const char * name) {
  307. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  308. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  309. if (striequals(ggml_backend_dev_name(dev), name)) {
  310. return dev;
  311. }
  312. }
  313. return nullptr;
  314. }
  315. ggml_backend_dev_t ggml_backend_dev_by_type(enum ggml_backend_dev_type type) {
  316. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  317. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  318. if (ggml_backend_dev_type(dev) == type) {
  319. return dev;
  320. }
  321. }
  322. return nullptr;
  323. }
  324. // Convenience functions
  325. ggml_backend_t ggml_backend_init_by_name(const char * name, const char * params) {
  326. ggml_backend_dev_t dev = ggml_backend_dev_by_name(name);
  327. if (!dev) {
  328. return nullptr;
  329. }
  330. return ggml_backend_dev_init(dev, params);
  331. }
  332. ggml_backend_t ggml_backend_init_by_type(enum ggml_backend_dev_type type, const char * params) {
  333. ggml_backend_dev_t dev = ggml_backend_dev_by_type(type);
  334. if (!dev) {
  335. return nullptr;
  336. }
  337. return ggml_backend_dev_init(dev, params);
  338. }
  339. ggml_backend_t ggml_backend_init_best(void) {
  340. ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU);
  341. if (!dev) {
  342. dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  343. }
  344. if (!dev) {
  345. return nullptr;
  346. }
  347. return ggml_backend_dev_init(dev, nullptr);
  348. }
  349. // Dynamic loading
  350. ggml_backend_reg_t ggml_backend_load(const char * path) {
  351. return get_reg().load_backend(utf8_to_utf16(path), false);
  352. }
  353. void ggml_backend_unload(ggml_backend_reg_t reg) {
  354. get_reg().unload_backend(reg, true);
  355. }
  356. static std::wstring get_executable_path() {
  357. #if defined(__APPLE__)
  358. // get executable path
  359. std::vector<char> path;
  360. uint32_t size;
  361. while (true) {
  362. size = path.size();
  363. if (_NSGetExecutablePath(path.data(), &size) == 0) {
  364. break;
  365. }
  366. path.resize(size);
  367. }
  368. std::string base_path(path.data(), size);
  369. // remove executable name
  370. auto last_slash = base_path.find_last_of('/');
  371. if (last_slash != std::string::npos) {
  372. base_path = base_path.substr(0, last_slash);
  373. }
  374. return utf8_to_utf16(base_path + "/");
  375. #elif defined(__linux__) || defined(__FreeBSD__)
  376. std::string base_path = ".";
  377. std::vector<char> path(1024);
  378. while (true) {
  379. // get executable path
  380. # if defined(__linux__)
  381. ssize_t len = readlink("/proc/self/exe", path.data(), path.size());
  382. # elif defined(__FreeBSD__)
  383. ssize_t len = readlink("/proc/curproc/file", path.data(), path.size());
  384. # endif
  385. if (len == -1) {
  386. break;
  387. }
  388. if (len < (ssize_t) path.size()) {
  389. base_path = std::string(path.data(), len);
  390. // remove executable name
  391. auto last_slash = base_path.find_last_of('/');
  392. if (last_slash != std::string::npos) {
  393. base_path = base_path.substr(0, last_slash);
  394. }
  395. break;
  396. }
  397. path.resize(path.size() * 2);
  398. }
  399. return utf8_to_utf16(base_path + "/");
  400. #elif defined(_WIN32)
  401. std::vector<wchar_t> path(MAX_PATH);
  402. DWORD len = GetModuleFileNameW(NULL, path.data(), path.size());
  403. if (len == 0) {
  404. return {};
  405. }
  406. std::wstring base_path(path.data(), len);
  407. // remove executable name
  408. auto last_slash = base_path.find_last_of('\\');
  409. if (last_slash != std::string::npos) {
  410. base_path = base_path.substr(0, last_slash);
  411. }
  412. return base_path + L"\\";
  413. #else
  414. return {};
  415. #endif
  416. }
  417. static std::wstring backend_filename_prefix() {
  418. #ifdef _WIN32
  419. return L"ggml-";
  420. #else
  421. return L"libggml-";
  422. #endif
  423. }
  424. static std::wstring backend_filename_suffix() {
  425. #ifdef _WIN32
  426. return L".dll";
  427. #else
  428. return L".so";
  429. #endif
  430. }
  431. static std::wstring path_separator() {
  432. #ifdef _WIN32
  433. return L"\\";
  434. #else
  435. return L"/";
  436. #endif
  437. }
  438. static ggml_backend_reg_t ggml_backend_load_best(const char * name, bool silent, const char * user_search_path) {
  439. // enumerate all the files that match [lib]ggml-name-*.[so|dll] in the search paths
  440. // TODO: search system paths
  441. std::wstring file_prefix = backend_filename_prefix() + utf8_to_utf16(name) + L"-";
  442. std::vector<std::wstring> search_paths;
  443. if (user_search_path == nullptr) {
  444. search_paths.push_back(L"." + path_separator());
  445. search_paths.push_back(get_executable_path());
  446. } else {
  447. search_paths.push_back(utf8_to_utf16(user_search_path) + path_separator());
  448. }
  449. int best_score = 0;
  450. std::wstring best_path;
  451. namespace fs = std::filesystem;
  452. for (const auto & search_path : search_paths) {
  453. if (!fs::exists(search_path)) {
  454. continue;
  455. }
  456. fs::directory_iterator dir_it(search_path, fs::directory_options::skip_permission_denied);
  457. for (const auto & entry : dir_it) {
  458. if (entry.is_regular_file()) {
  459. std::wstring filename = entry.path().filename().wstring();
  460. std::wstring ext = entry.path().extension().wstring();
  461. if (filename.find(file_prefix) == 0 && ext == backend_filename_suffix()) {
  462. dl_handle_ptr handle { dl_load_library(entry.path().wstring()) };
  463. if (!handle && !silent) {
  464. GGML_LOG_ERROR("%s: failed to load %s\n", __func__, utf16_to_utf8(entry.path().wstring()).c_str());
  465. }
  466. if (handle) {
  467. auto score_fn = (ggml_backend_score_t) dl_get_sym(handle.get(), "ggml_backend_score");
  468. if (score_fn) {
  469. int s = score_fn();
  470. #ifndef NDEBUG
  471. GGML_LOG_DEBUG("%s: %s score: %d\n", __func__, utf16_to_utf8(entry.path().wstring()).c_str(), s);
  472. #endif
  473. if (s > best_score) {
  474. best_score = s;
  475. best_path = entry.path().wstring();
  476. }
  477. } else {
  478. if (!silent) {
  479. GGML_LOG_INFO("%s: failed to find ggml_backend_score in %s\n", __func__, utf16_to_utf8(entry.path().wstring()).c_str());
  480. }
  481. }
  482. }
  483. }
  484. }
  485. }
  486. }
  487. if (best_score == 0) {
  488. // try to load the base backend
  489. for (const auto & search_path : search_paths) {
  490. std::wstring path = search_path + backend_filename_prefix() + utf8_to_utf16(name) + backend_filename_suffix();
  491. if (fs::exists(path)) {
  492. return get_reg().load_backend(path, silent);
  493. }
  494. }
  495. return nullptr;
  496. }
  497. return get_reg().load_backend(best_path, silent);
  498. }
  499. void ggml_backend_load_all() {
  500. ggml_backend_load_all_from_path(nullptr);
  501. }
  502. void ggml_backend_load_all_from_path(const char * dir_path) {
  503. #ifdef NDEBUG
  504. bool silent = true;
  505. #else
  506. bool silent = false;
  507. #endif
  508. ggml_backend_load_best("blas", silent, dir_path);
  509. ggml_backend_load_best("cann", silent, dir_path);
  510. ggml_backend_load_best("cuda", silent, dir_path);
  511. ggml_backend_load_best("hip", silent, dir_path);
  512. ggml_backend_load_best("kompute", silent, dir_path);
  513. ggml_backend_load_best("metal", silent, dir_path);
  514. ggml_backend_load_best("rpc", silent, dir_path);
  515. ggml_backend_load_best("sycl", silent, dir_path);
  516. ggml_backend_load_best("vulkan", silent, dir_path);
  517. ggml_backend_load_best("opencl", silent, dir_path);
  518. ggml_backend_load_best("musa", silent, dir_path);
  519. ggml_backend_load_best("cpu", silent, dir_path);
  520. }