rpc-server.cpp 10 KB

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