1
0

rpc-server.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. #ifdef __linux__
  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. #endif // __linux__
  119. cache_directory = ensure_trailing_slash(cache_directory);
  120. cache_directory += "llama.cpp";
  121. }
  122. return ensure_trailing_slash(cache_directory);
  123. }
  124. struct rpc_server_params {
  125. std::string host = "127.0.0.1";
  126. int port = 50052;
  127. size_t backend_mem = 0;
  128. bool use_cache = false;
  129. };
  130. static void print_usage(int /*argc*/, char ** argv, rpc_server_params params) {
  131. fprintf(stderr, "Usage: %s [options]\n\n", argv[0]);
  132. fprintf(stderr, "options:\n");
  133. fprintf(stderr, " -h, --help show this help message and exit\n");
  134. fprintf(stderr, " -H HOST, --host HOST host to bind to (default: %s)\n", params.host.c_str());
  135. fprintf(stderr, " -p PORT, --port PORT port to bind to (default: %d)\n", params.port);
  136. fprintf(stderr, " -m MEM, --mem MEM backend memory size (in MB)\n");
  137. fprintf(stderr, " -c, --cache enable local file cache\n");
  138. fprintf(stderr, "\n");
  139. }
  140. static bool rpc_server_params_parse(int argc, char ** argv, rpc_server_params & params) {
  141. std::string arg;
  142. for (int i = 1; i < argc; i++) {
  143. arg = argv[i];
  144. if (arg == "-H" || arg == "--host") {
  145. if (++i >= argc) {
  146. return false;
  147. }
  148. params.host = argv[i];
  149. } else if (arg == "-p" || arg == "--port") {
  150. if (++i >= argc) {
  151. return false;
  152. }
  153. params.port = std::stoi(argv[i]);
  154. if (params.port <= 0 || params.port > 65535) {
  155. return false;
  156. }
  157. } else if (arg == "-c" || arg == "--cache") {
  158. params.use_cache = true;
  159. } else if (arg == "-m" || arg == "--mem") {
  160. if (++i >= argc) {
  161. return false;
  162. }
  163. params.backend_mem = std::stoul(argv[i]) * 1024 * 1024;
  164. } else if (arg == "-h" || arg == "--help") {
  165. print_usage(argc, argv, params);
  166. exit(0);
  167. } else {
  168. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  169. print_usage(argc, argv, params);
  170. exit(0);
  171. }
  172. }
  173. return true;
  174. }
  175. static ggml_backend_t create_backend() {
  176. ggml_backend_t backend = NULL;
  177. #ifdef GGML_USE_CUDA
  178. fprintf(stderr, "%s: using CUDA backend\n", __func__);
  179. backend = ggml_backend_cuda_init(0); // init device 0
  180. if (!backend) {
  181. fprintf(stderr, "%s: ggml_backend_cuda_init() failed\n", __func__);
  182. }
  183. #elif GGML_USE_METAL
  184. fprintf(stderr, "%s: using Metal backend\n", __func__);
  185. backend = ggml_backend_metal_init();
  186. if (!backend) {
  187. fprintf(stderr, "%s: ggml_backend_metal_init() failed\n", __func__);
  188. }
  189. #elif GGML_USE_VULKAN
  190. fprintf(stderr, "%s: using Vulkan backend\n", __func__);
  191. backend = ggml_backend_vk_init(0); // init device 0
  192. if (!backend) {
  193. fprintf(stderr, "%s: ggml_backend_vulkan_init() failed\n", __func__);
  194. }
  195. #elif GGML_USE_SYCL
  196. fprintf(stderr, "%s: using SYCL backend\n", __func__);
  197. backend = ggml_backend_sycl_init(0); // init device 0
  198. if (!backend) {
  199. fprintf(stderr, "%s: ggml_backend_sycl_init() failed\n", __func__);
  200. }
  201. #endif
  202. // if there aren't GPU Backends fallback to CPU backend
  203. if (!backend) {
  204. fprintf(stderr, "%s: using CPU backend\n", __func__);
  205. backend = ggml_backend_cpu_init();
  206. }
  207. return backend;
  208. }
  209. static void get_backend_memory(size_t * free_mem, size_t * total_mem) {
  210. #ifdef GGML_USE_CUDA
  211. ggml_backend_cuda_get_device_memory(0, free_mem, total_mem);
  212. #elif GGML_USE_VULKAN
  213. ggml_backend_vk_get_device_memory(0, free_mem, total_mem);
  214. #elif GGML_USE_SYCL
  215. ggml_backend_sycl_get_device_memory(0, free_mem, total_mem);
  216. #else
  217. #ifdef _WIN32
  218. MEMORYSTATUSEX status;
  219. status.dwLength = sizeof(status);
  220. GlobalMemoryStatusEx(&status);
  221. *total_mem = status.ullTotalPhys;
  222. *free_mem = status.ullAvailPhys;
  223. #else
  224. long pages = sysconf(_SC_PHYS_PAGES);
  225. long page_size = sysconf(_SC_PAGE_SIZE);
  226. *total_mem = pages * page_size;
  227. *free_mem = *total_mem;
  228. #endif
  229. #endif
  230. }
  231. int main(int argc, char * argv[]) {
  232. rpc_server_params params;
  233. if (!rpc_server_params_parse(argc, argv, params)) {
  234. fprintf(stderr, "Invalid parameters\n");
  235. return 1;
  236. }
  237. if (params.host != "127.0.0.1") {
  238. fprintf(stderr, "\n");
  239. fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  240. fprintf(stderr, "WARNING: Host ('%s') is != '127.0.0.1'\n", params.host.c_str());
  241. fprintf(stderr, " Never expose the RPC server to an open network!\n");
  242. fprintf(stderr, " This is an experimental feature and is not secure!\n");
  243. fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  244. fprintf(stderr, "\n");
  245. }
  246. ggml_backend_t backend = create_backend();
  247. if (!backend) {
  248. fprintf(stderr, "Failed to create backend\n");
  249. return 1;
  250. }
  251. std::string endpoint = params.host + ":" + std::to_string(params.port);
  252. size_t free_mem, total_mem;
  253. if (params.backend_mem > 0) {
  254. free_mem = params.backend_mem;
  255. total_mem = params.backend_mem;
  256. } else {
  257. get_backend_memory(&free_mem, &total_mem);
  258. }
  259. const char * cache_dir = nullptr;
  260. std::string cache_dir_str = fs_get_cache_directory() + "rpc/";
  261. if (params.use_cache) {
  262. if (!fs_create_directory_with_parents(cache_dir_str)) {
  263. fprintf(stderr, "Failed to create cache directory: %s\n", cache_dir_str.c_str());
  264. return 1;
  265. }
  266. cache_dir = cache_dir_str.c_str();
  267. }
  268. printf("Starting RPC server\n");
  269. printf(" endpoint : %s\n", endpoint.c_str());
  270. printf(" local cache : %s\n", cache_dir ? cache_dir : "n/a");
  271. printf(" backend memory : %zu MB\n", free_mem / (1024 * 1024));
  272. ggml_backend_rpc_start_server(backend, endpoint.c_str(), cache_dir, free_mem, total_mem);
  273. ggml_backend_free(backend);
  274. return 0;
  275. }