1
0

rpc-server.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #if defined(_MSC_VER)
  2. #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
  3. #endif
  4. #include "ggml-cpu.h"
  5. #ifdef GGML_USE_CUDA
  6. #include "ggml-cuda.h"
  7. #endif
  8. #ifdef GGML_USE_METAL
  9. #include "ggml-metal.h"
  10. #endif
  11. #ifdef GGML_USE_VULKAN
  12. #include "ggml-vulkan.h"
  13. #endif
  14. #ifdef GGML_USE_SYCL
  15. #include "ggml-sycl.h"
  16. #endif
  17. #include "ggml-rpc.h"
  18. #ifdef _WIN32
  19. # define NOMINMAX
  20. # define DIRECTORY_SEPARATOR '\\'
  21. # include <locale>
  22. # include <windows.h>
  23. # include <fcntl.h>
  24. # include <io.h>
  25. #else
  26. # define DIRECTORY_SEPARATOR '/'
  27. # include <unistd.h>
  28. # include <sys/stat.h>
  29. #endif
  30. #include <codecvt>
  31. #include <string>
  32. #include <stdio.h>
  33. #include <vector>
  34. #include <filesystem>
  35. #include <algorithm>
  36. #include <thread>
  37. namespace fs = std::filesystem;
  38. // NOTE: this is copied from common.cpp to avoid linking with libcommon
  39. // returns true if successful, false otherwise
  40. static bool fs_create_directory_with_parents(const std::string & path) {
  41. #ifdef _WIN32
  42. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  43. std::wstring wpath = converter.from_bytes(path);
  44. // if the path already exists, check whether it's a directory
  45. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  46. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  47. return true;
  48. }
  49. size_t pos_slash = 0;
  50. // process path from front to back, procedurally creating directories
  51. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  52. const std::wstring subpath = wpath.substr(0, pos_slash);
  53. const wchar_t * test = subpath.c_str();
  54. const bool success = CreateDirectoryW(test, NULL);
  55. if (!success) {
  56. const DWORD error = GetLastError();
  57. // if the path already exists, ensure that it's a directory
  58. if (error == ERROR_ALREADY_EXISTS) {
  59. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  60. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  61. return false;
  62. }
  63. } else {
  64. return false;
  65. }
  66. }
  67. pos_slash += 1;
  68. }
  69. return true;
  70. #else
  71. // if the path already exists, check whether it's a directory
  72. struct stat info;
  73. if (stat(path.c_str(), &info) == 0) {
  74. return S_ISDIR(info.st_mode);
  75. }
  76. size_t pos_slash = 1; // skip leading slashes for directory creation
  77. // process path from front to back, procedurally creating directories
  78. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  79. const std::string subpath = path.substr(0, pos_slash);
  80. struct stat info;
  81. // if the path already exists, ensure that it's a directory
  82. if (stat(subpath.c_str(), &info) == 0) {
  83. if (!S_ISDIR(info.st_mode)) {
  84. return false;
  85. }
  86. } else {
  87. // create parent directories
  88. const int ret = mkdir(subpath.c_str(), 0755);
  89. if (ret != 0) {
  90. return false;
  91. }
  92. }
  93. pos_slash += 1;
  94. }
  95. return true;
  96. #endif // _WIN32
  97. }
  98. // NOTE: this is copied from common.cpp to avoid linking with libcommon
  99. static std::string fs_get_cache_directory() {
  100. std::string cache_directory = "";
  101. auto ensure_trailing_slash = [](std::string p) {
  102. // Make sure to add trailing slash
  103. if (p.back() != DIRECTORY_SEPARATOR) {
  104. p += DIRECTORY_SEPARATOR;
  105. }
  106. return p;
  107. };
  108. if (getenv("LLAMA_CACHE")) {
  109. cache_directory = std::getenv("LLAMA_CACHE");
  110. } else {
  111. #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX)
  112. if (std::getenv("XDG_CACHE_HOME")) {
  113. cache_directory = std::getenv("XDG_CACHE_HOME");
  114. } else {
  115. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  116. }
  117. #elif defined(__APPLE__)
  118. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  119. #elif defined(_WIN32)
  120. cache_directory = std::getenv("LOCALAPPDATA");
  121. #else
  122. # error Unknown architecture
  123. #endif
  124. cache_directory = ensure_trailing_slash(cache_directory);
  125. cache_directory += "llama.cpp";
  126. }
  127. return ensure_trailing_slash(cache_directory);
  128. }
  129. struct rpc_server_params {
  130. std::string host = "127.0.0.1";
  131. int port = 50052;
  132. size_t backend_mem = 0;
  133. bool use_cache = false;
  134. int n_threads = std::max(1U, std::thread::hardware_concurrency()/2);
  135. };
  136. static void print_usage(int /*argc*/, char ** argv, rpc_server_params params) {
  137. fprintf(stderr, "Usage: %s [options]\n\n", argv[0]);
  138. fprintf(stderr, "options:\n");
  139. fprintf(stderr, " -h, --help show this help message and exit\n");
  140. fprintf(stderr, " -t, --threads number of threads for the CPU backend (default: %d)\n", params.n_threads);
  141. fprintf(stderr, " -H HOST, --host HOST host to bind to (default: %s)\n", params.host.c_str());
  142. fprintf(stderr, " -p PORT, --port PORT port to bind to (default: %d)\n", params.port);
  143. fprintf(stderr, " -m MEM, --mem MEM backend memory size (in MB)\n");
  144. fprintf(stderr, " -c, --cache enable local file cache\n");
  145. fprintf(stderr, "\n");
  146. }
  147. static bool rpc_server_params_parse(int argc, char ** argv, rpc_server_params & params) {
  148. std::string arg;
  149. for (int i = 1; i < argc; i++) {
  150. arg = argv[i];
  151. if (arg == "-H" || arg == "--host") {
  152. if (++i >= argc) {
  153. return false;
  154. }
  155. params.host = argv[i];
  156. } else if (arg == "-t" || arg == "--threads") {
  157. if (++i >= argc) {
  158. return false;
  159. }
  160. params.n_threads = std::stoi(argv[i]);
  161. if (params.n_threads <= 0) {
  162. fprintf(stderr, "error: invalid number of threads: %d\n", params.n_threads);
  163. return false;
  164. }
  165. } else if (arg == "-p" || arg == "--port") {
  166. if (++i >= argc) {
  167. return false;
  168. }
  169. params.port = std::stoi(argv[i]);
  170. if (params.port <= 0 || params.port > 65535) {
  171. return false;
  172. }
  173. } else if (arg == "-c" || arg == "--cache") {
  174. params.use_cache = true;
  175. } else if (arg == "-m" || arg == "--mem") {
  176. if (++i >= argc) {
  177. return false;
  178. }
  179. params.backend_mem = std::stoul(argv[i]) * 1024 * 1024;
  180. } else if (arg == "-h" || arg == "--help") {
  181. print_usage(argc, argv, params);
  182. exit(0);
  183. } else {
  184. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  185. print_usage(argc, argv, params);
  186. exit(0);
  187. }
  188. }
  189. return true;
  190. }
  191. static ggml_backend_t create_backend(const rpc_server_params & params) {
  192. ggml_backend_t backend = NULL;
  193. #ifdef GGML_USE_CUDA
  194. fprintf(stderr, "%s: using CUDA backend\n", __func__);
  195. backend = ggml_backend_cuda_init(0); // init device 0
  196. if (!backend) {
  197. fprintf(stderr, "%s: ggml_backend_cuda_init() failed\n", __func__);
  198. }
  199. #elif GGML_USE_METAL
  200. fprintf(stderr, "%s: using Metal backend\n", __func__);
  201. backend = ggml_backend_metal_init();
  202. if (!backend) {
  203. fprintf(stderr, "%s: ggml_backend_metal_init() failed\n", __func__);
  204. }
  205. #elif GGML_USE_VULKAN
  206. fprintf(stderr, "%s: using Vulkan backend\n", __func__);
  207. backend = ggml_backend_vk_init(0); // init device 0
  208. if (!backend) {
  209. fprintf(stderr, "%s: ggml_backend_vulkan_init() failed\n", __func__);
  210. }
  211. #elif GGML_USE_SYCL
  212. fprintf(stderr, "%s: using SYCL backend\n", __func__);
  213. backend = ggml_backend_sycl_init(0); // init device 0
  214. if (!backend) {
  215. fprintf(stderr, "%s: ggml_backend_sycl_init() failed\n", __func__);
  216. }
  217. #endif
  218. // if there aren't GPU Backends fallback to CPU backend
  219. if (!backend) {
  220. fprintf(stderr, "%s: using CPU backend\n", __func__);
  221. backend = ggml_backend_cpu_init();
  222. ggml_backend_cpu_set_n_threads(backend, params.n_threads);
  223. }
  224. return backend;
  225. }
  226. static void get_backend_memory(size_t * free_mem, size_t * total_mem) {
  227. #ifdef GGML_USE_CUDA
  228. ggml_backend_cuda_get_device_memory(0, free_mem, total_mem);
  229. #elif GGML_USE_VULKAN
  230. ggml_backend_vk_get_device_memory(0, free_mem, total_mem);
  231. #elif GGML_USE_SYCL
  232. ggml_backend_sycl_get_device_memory(0, free_mem, total_mem);
  233. #else
  234. #ifdef _WIN32
  235. MEMORYSTATUSEX status;
  236. status.dwLength = sizeof(status);
  237. GlobalMemoryStatusEx(&status);
  238. *total_mem = status.ullTotalPhys;
  239. *free_mem = status.ullAvailPhys;
  240. #else
  241. long pages = sysconf(_SC_PHYS_PAGES);
  242. long page_size = sysconf(_SC_PAGE_SIZE);
  243. *total_mem = pages * page_size;
  244. *free_mem = *total_mem;
  245. #endif
  246. #endif
  247. }
  248. int main(int argc, char * argv[]) {
  249. rpc_server_params params;
  250. if (!rpc_server_params_parse(argc, argv, params)) {
  251. fprintf(stderr, "Invalid parameters\n");
  252. return 1;
  253. }
  254. if (params.host != "127.0.0.1") {
  255. fprintf(stderr, "\n");
  256. fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  257. fprintf(stderr, "WARNING: Host ('%s') is != '127.0.0.1'\n", params.host.c_str());
  258. fprintf(stderr, " Never expose the RPC server to an open network!\n");
  259. fprintf(stderr, " This is an experimental feature and is not secure!\n");
  260. fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  261. fprintf(stderr, "\n");
  262. }
  263. ggml_backend_t backend = create_backend(params);
  264. if (!backend) {
  265. fprintf(stderr, "Failed to create backend\n");
  266. return 1;
  267. }
  268. std::string endpoint = params.host + ":" + std::to_string(params.port);
  269. size_t free_mem, total_mem;
  270. if (params.backend_mem > 0) {
  271. free_mem = params.backend_mem;
  272. total_mem = params.backend_mem;
  273. } else {
  274. get_backend_memory(&free_mem, &total_mem);
  275. }
  276. const char * cache_dir = nullptr;
  277. std::string cache_dir_str;
  278. if (params.use_cache) {
  279. cache_dir_str = fs_get_cache_directory() + "rpc/";
  280. if (!fs_create_directory_with_parents(cache_dir_str)) {
  281. fprintf(stderr, "Failed to create cache directory: %s\n", cache_dir_str.c_str());
  282. return 1;
  283. }
  284. cache_dir = cache_dir_str.c_str();
  285. }
  286. printf("Starting RPC server v%d.%d.%d\n",
  287. RPC_PROTO_MAJOR_VERSION,
  288. RPC_PROTO_MINOR_VERSION,
  289. RPC_PROTO_PATCH_VERSION);
  290. printf(" endpoint : %s\n", endpoint.c_str());
  291. printf(" local cache : %s\n", cache_dir ? cache_dir : "n/a");
  292. printf(" backend memory : %zu MB\n", free_mem / (1024 * 1024));
  293. ggml_backend_rpc_start_server(backend, endpoint.c_str(), cache_dir, free_mem, total_mem);
  294. ggml_backend_free(backend);
  295. return 0;
  296. }