1#include "ggml-rpc.h"
2#ifdef _WIN32
3# define NOMINMAX
4# define DIRECTORY_SEPARATOR '\\'
5# include <windows.h>
6# include <fcntl.h>
7# include <io.h>
8#else
9# define DIRECTORY_SEPARATOR '/'
10# include <unistd.h>
11# include <sys/stat.h>
12#endif
13#include <string>
14#include <stdio.h>
15#include <vector>
16#include <algorithm>
17#include <thread>
18#include <regex>
19
20#if defined(__linux__)
21#include <sys/types.h>
22#include <pwd.h>
23#endif
24
25// NOTE: this is copied from common.cpp to avoid linking with libcommon
26#ifdef _WIN32
27static std::wstring utf8_to_wstring(const std::string & str) {
28 if (str.empty()) {
29 return std::wstring();
30 }
31
32 int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
33
34 if (size <= 0) {
35 return std::wstring();
36 }
37
38 std::wstring wstr(size, 0);
39 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], size);
40
41 return wstr;
42}
43#endif
44
45// NOTE: this is copied from common.cpp to avoid linking with libcommon
46// returns true if successful, false otherwise
47static bool fs_create_directory_with_parents(const std::string & path) {
48#ifdef _WIN32
49 std::wstring wpath = utf8_to_wstring(path);
50
51 // if the path already exists, check whether it's a directory
52 const DWORD attributes = GetFileAttributesW(wpath.c_str());
53 if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
54 return true;
55 }
56
57 size_t pos_slash = 0;
58
59 // process path from front to back, procedurally creating directories
60 while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
61 const std::wstring subpath = wpath.substr(0, pos_slash);
62
63 pos_slash += 1;
64
65 // skip the drive letter, in some systems it can return an access denied error
66 if (subpath.length() == 2 && subpath[1] == ':') {
67 continue;
68 }
69
70 const bool success = CreateDirectoryW(subpath.c_str(), NULL);
71
72 if (!success) {
73 const DWORD error = GetLastError();
74
75 // if the path already exists, ensure that it's a directory
76 if (error == ERROR_ALREADY_EXISTS) {
77 const DWORD attributes = GetFileAttributesW(subpath.c_str());
78 if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
79 return false;
80 }
81 } else {
82 return false;
83 }
84 }
85 }
86
87 return true;
88#else
89 // if the path already exists, check whether it's a directory
90 struct stat info;
91 if (stat(path.c_str(), &info) == 0) {
92 return S_ISDIR(info.st_mode);
93 }
94
95 size_t pos_slash = 1; // skip leading slashes for directory creation
96
97 // process path from front to back, procedurally creating directories
98 while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
99 const std::string subpath = path.substr(0, pos_slash);
100 struct stat info;
101
102 // if the path already exists, ensure that it's a directory
103 if (stat(subpath.c_str(), &info) == 0) {
104 if (!S_ISDIR(info.st_mode)) {
105 return false;
106 }
107 } else {
108 // create parent directories
109 const int ret = mkdir(subpath.c_str(), 0755);
110 if (ret != 0) {
111 return false;
112 }
113 }
114
115 pos_slash += 1;
116 }
117
118 return true;
119#endif // _WIN32
120}
121
122// NOTE: this is copied from common.cpp to avoid linking with libcommon
123static std::string fs_get_cache_directory() {
124 std::string cache_directory = "";
125 auto ensure_trailing_slash = [](std::string p) {
126 // Make sure to add trailing slash
127 if (p.back() != DIRECTORY_SEPARATOR) {
128 p += DIRECTORY_SEPARATOR;
129 }
130 return p;
131 };
132 if (getenv("LLAMA_CACHE")) {
133 cache_directory = std::getenv("LLAMA_CACHE");
134 } else {
135#if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
136 if (std::getenv("XDG_CACHE_HOME")) {
137 cache_directory = std::getenv("XDG_CACHE_HOME");
138 } else if (std::getenv("HOME")) {
139 cache_directory = std::getenv("HOME") + std::string("/.cache/");
140 } else {
141#if defined(__linux__)
142 /* no $HOME is defined, fallback to getpwuid */
143 struct passwd *pw = getpwuid(getuid());
144 if ((!pw) || (!pw->pw_dir)) {
145 throw std::runtime_error("Failed to find $HOME directory");
146 }
147
148 cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
149#else /* defined(__linux__) */
150 throw std::runtime_error("Failed to find $HOME directory");
151#endif /* defined(__linux__) */
152 }
153#elif defined(__APPLE__)
154 cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
155#elif defined(_WIN32)
156 cache_directory = std::getenv("LOCALAPPDATA");
157#elif defined(__EMSCRIPTEN__)
158 GGML_ABORT("not implemented on this platform");
159#else
160# error Unknown architecture
161#endif
162 cache_directory = ensure_trailing_slash(cache_directory);
163 cache_directory += "llama.cpp";
164 }
165 return ensure_trailing_slash(cache_directory);
166}
167
168struct rpc_server_params {
169 std::string host = "127.0.0.1";
170 int port = 50052;
171 bool use_cache = false;
172 int n_threads = std::max(1U, std::thread::hardware_concurrency()/2);
173 std::vector<std::string> devices;
174};
175
176static void print_usage(int /*argc*/, char ** argv, rpc_server_params params) {
177 fprintf(stderr, "Usage: %s [options]\n\n", argv[0]);
178 fprintf(stderr, "options:\n");
179 fprintf(stderr, " -h, --help show this help message and exit\n");
180 fprintf(stderr, " -t, --threads N number of threads for the CPU device (default: %d)\n", params.n_threads);
181 fprintf(stderr, " -d, --device <dev1,dev2,...> comma-separated list of devices\n");
182 fprintf(stderr, " -H, --host HOST host to bind to (default: %s)\n", params.host.c_str());
183 fprintf(stderr, " -p, --port PORT port to bind to (default: %d)\n", params.port);
184 fprintf(stderr, " -c, --cache enable local file cache\n");
185 fprintf(stderr, "\n");
186}
187
188static bool rpc_server_params_parse(int argc, char ** argv, rpc_server_params & params) {
189 std::string arg;
190 for (int i = 1; i < argc; i++) {
191 arg = argv[i];
192 if (arg == "-H" || arg == "--host") {
193 if (++i >= argc) {
194 return false;
195 }
196 params.host = argv[i];
197 } else if (arg == "-t" || arg == "--threads") {
198 if (++i >= argc) {
199 return false;
200 }
201 params.n_threads = std::stoi(argv[i]);
202 if (params.n_threads <= 0) {
203 fprintf(stderr, "error: invalid number of threads: %d\n", params.n_threads);
204 return false;
205 }
206 } else if (arg == "-d" || arg == "--device") {
207 if (++i >= argc) {
208 return false;
209 }
210 const std::regex regex{ R"([,/]+)" };
211 std::string dev_str = argv[i];
212 std::sregex_token_iterator iter(dev_str.begin(), dev_str.end(), regex, -1);
213 std::sregex_token_iterator end;
214 for ( ; iter != end; ++iter) {
215 try {
216 params.devices.push_back(*iter);
217 } catch (const std::exception & ) {
218 fprintf(stderr, "error: invalid device: %s\n", iter->str().c_str());
219 return false;
220 }
221 }
222 } else if (arg == "-p" || arg == "--port") {
223 if (++i >= argc) {
224 return false;
225 }
226 params.port = std::stoi(argv[i]);
227 if (params.port <= 0 || params.port > 65535) {
228 return false;
229 }
230 } else if (arg == "-c" || arg == "--cache") {
231 params.use_cache = true;
232 } else if (arg == "-h" || arg == "--help") {
233 print_usage(argc, argv, params);
234 exit(0);
235 } else {
236 fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
237 print_usage(argc, argv, params);
238 exit(0);
239 }
240 }
241 return true;
242}
243
244static std::vector<ggml_backend_dev_t> get_devices(const rpc_server_params & params) {
245 std::vector<ggml_backend_dev_t> devices;
246 if (!params.devices.empty()) {
247 for (auto device : params.devices) {
248 ggml_backend_dev_t dev = ggml_backend_dev_by_name(device.c_str());
249 if (dev) {
250 devices.push_back(dev);
251 } else {
252 fprintf(stderr, "error: unknown device: %s\n", device.c_str());
253 fprintf(stderr, "available devices:\n");
254 for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
255 auto * dev = ggml_backend_dev_get(i);
256 size_t free, total;
257 ggml_backend_dev_memory(dev, &free, &total);
258 printf(" %s: %s (%zu MiB, %zu MiB free)\n", ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), total / 1024 / 1024, free / 1024 / 1024);
259 }
260 return {};
261 }
262 }
263 }
264
265 // Try non-CPU devices first
266 if (devices.empty()) {
267 for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
268 ggml_backend_dev_t dev = ggml_backend_dev_get(i);
269 if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_CPU) {
270 devices.push_back(dev);
271 }
272 }
273 }
274
275 // If there are no accelerators, fallback to CPU device
276 if (devices.empty()) {
277 ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
278 if (dev) {
279 devices.push_back(dev);
280 }
281 }
282
283 return devices;
284}
285
286int main(int argc, char * argv[]) {
287 ggml_backend_load_all();
288
289 rpc_server_params params;
290 if (!rpc_server_params_parse(argc, argv, params)) {
291 fprintf(stderr, "Invalid parameters\n");
292 return 1;
293 }
294
295 if (params.host != "127.0.0.1") {
296 fprintf(stderr, "\n");
297 fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
298 fprintf(stderr, "WARNING: Host ('%s') is != '127.0.0.1'\n", params.host.c_str());
299 fprintf(stderr, " Never expose the RPC server to an open network!\n");
300 fprintf(stderr, " This is an experimental feature and is not secure!\n");
301 fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
302 fprintf(stderr, "\n");
303 }
304
305 auto devices = get_devices(params);
306 if (devices.empty()) {
307 fprintf(stderr, "No devices found\n");
308 return 1;
309 }
310 std::string endpoint = params.host + ":" + std::to_string(params.port);
311 const char * cache_dir = nullptr;
312 std::string cache_dir_str;
313 if (params.use_cache) {
314 cache_dir_str = fs_get_cache_directory() + "rpc/";
315 if (!fs_create_directory_with_parents(cache_dir_str)) {
316 fprintf(stderr, "Failed to create cache directory: %s\n", cache_dir_str.c_str());
317 return 1;
318 }
319 cache_dir = cache_dir_str.c_str();
320 }
321
322 ggml_backend_reg_t reg = ggml_backend_reg_by_name("RPC");
323 if (!reg) {
324 fprintf(stderr, "Failed to find RPC backend\n");
325 return 1;
326 }
327
328 auto start_server_fn = (decltype(ggml_backend_rpc_start_server)*) ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_start_server");
329 if (!start_server_fn) {
330 fprintf(stderr, "Failed to obtain RPC backend start server function\n");
331 return 1;
332 }
333
334 start_server_fn(endpoint.c_str(), cache_dir, params.n_threads, devices.size(), devices.data());
335 return 0;
336}