llama_cpp 0.15.1 → 0.15.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1155 @@
1
+ #include "ggml-rpc.h"
2
+ #include "ggml.h"
3
+ #include "ggml-backend-impl.h"
4
+
5
+ #include <cinttypes>
6
+ #include <string>
7
+ #include <vector>
8
+ #include <memory>
9
+ #include <unordered_map>
10
+ #include <unordered_set>
11
+ #ifdef _WIN32
12
+ # define WIN32_LEAN_AND_MEAN
13
+ # ifndef NOMINMAX
14
+ # define NOMINMAX
15
+ # endif
16
+ # include <windows.h>
17
+ # include <winsock2.h>
18
+ #else
19
+ # include <arpa/inet.h>
20
+ # include <sys/socket.h>
21
+ # include <sys/types.h>
22
+ # include <netinet/in.h>
23
+ # include <netinet/tcp.h>
24
+ # include <netdb.h>
25
+ # include <unistd.h>
26
+ #endif
27
+ #include <string.h>
28
+
29
+ #define UNUSED GGML_UNUSED
30
+
31
+ #define GGML_DEBUG 0
32
+ #if (GGML_DEBUG >= 1)
33
+ #define GGML_PRINT_DEBUG(...) printf(__VA_ARGS__)
34
+ #else
35
+ #define GGML_PRINT_DEBUG(...)
36
+ #endif
37
+
38
+ #ifdef _WIN32
39
+ typedef SOCKET sockfd_t;
40
+ using ssize_t = __int64;
41
+ #else
42
+ typedef int sockfd_t;
43
+ #endif
44
+
45
+ // cross-platform socket
46
+ struct socket_t {
47
+ sockfd_t fd;
48
+ socket_t(sockfd_t fd) : fd(fd) {}
49
+ ~socket_t() {
50
+ #ifdef _WIN32
51
+ closesocket(this->fd);
52
+ #else
53
+ close(this->fd);
54
+ #endif
55
+ }
56
+ };
57
+
58
+ // ggml_tensor is serialized into rpc_tensor
59
+ #pragma pack(push, 1)
60
+ struct rpc_tensor {
61
+ uint64_t id;
62
+ uint32_t type;
63
+ uint64_t buffer;
64
+ uint32_t ne[GGML_MAX_DIMS];
65
+ uint32_t nb[GGML_MAX_DIMS];
66
+ uint32_t op;
67
+ int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
68
+ int32_t flags;
69
+ uint64_t src[GGML_MAX_SRC];
70
+ uint64_t view_src;
71
+ uint64_t view_offs;
72
+ uint64_t data;
73
+ char name[GGML_MAX_NAME];
74
+ };
75
+ #pragma pack(pop)
76
+
77
+ // RPC commands
78
+ enum rpc_cmd {
79
+ ALLOC_BUFFER = 0,
80
+ GET_ALIGNMENT,
81
+ GET_MAX_SIZE,
82
+ BUFFER_GET_BASE,
83
+ FREE_BUFFER,
84
+ BUFFER_CLEAR,
85
+ SET_TENSOR,
86
+ GET_TENSOR,
87
+ COPY_TENSOR,
88
+ GRAPH_COMPUTE,
89
+ GET_DEVICE_MEMORY,
90
+ };
91
+
92
+ // RPC data structures
93
+
94
+ static ggml_guid_t ggml_backend_rpc_guid() {
95
+ static ggml_guid guid = {0x99, 0x68, 0x5b, 0x6c, 0xd2, 0x83, 0x3d, 0x24, 0x25, 0x36, 0x72, 0xe1, 0x5b, 0x0e, 0x14, 0x03};
96
+ return &guid;
97
+ }
98
+
99
+ struct ggml_backend_rpc_buffer_type_context {
100
+ std::shared_ptr<socket_t> sock;
101
+ std::string name;
102
+ size_t alignment;
103
+ size_t max_size;
104
+ };
105
+
106
+ struct ggml_backend_rpc_context {
107
+ std::string endpoint;
108
+ std::string name;
109
+ std::shared_ptr<socket_t> sock;
110
+ ggml_backend_buffer_type_t buft;
111
+ };
112
+
113
+ struct ggml_backend_rpc_buffer_context {
114
+ std::shared_ptr<socket_t> sock;
115
+ std::unordered_map<ggml_backend_buffer_t, void *> base_cache;
116
+ uint64_t remote_ptr;
117
+ std::string name;
118
+ };
119
+
120
+ // RPC helper functions
121
+
122
+ static std::shared_ptr<socket_t> make_socket(sockfd_t fd) {
123
+ #ifdef _WIN32
124
+ if (fd == INVALID_SOCKET) {
125
+ return nullptr;
126
+ }
127
+ #else
128
+ if (fd < 0) {
129
+ return nullptr;
130
+ }
131
+ #endif
132
+ return std::make_shared<socket_t>(fd);
133
+ }
134
+
135
+ static bool set_no_delay(sockfd_t sockfd) {
136
+ int flag = 1;
137
+ // set TCP_NODELAY to disable Nagle's algorithm
138
+ int ret = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
139
+ return ret == 0;
140
+ }
141
+
142
+ static bool set_reuse_addr(sockfd_t sockfd) {
143
+ int flag = 1;
144
+ int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int));
145
+ return ret == 0;
146
+ }
147
+
148
+ static std::shared_ptr<socket_t> socket_connect(const char * host, int port) {
149
+ struct sockaddr_in addr;
150
+ auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
151
+ auto sock_ptr = make_socket(sockfd);
152
+ if (sock_ptr == nullptr) {
153
+ return nullptr;
154
+ }
155
+ if (!set_no_delay(sockfd)) {
156
+ fprintf(stderr, "Failed to set TCP_NODELAY\n");
157
+ return nullptr;
158
+ }
159
+ addr.sin_family = AF_INET;
160
+ addr.sin_port = htons(port);
161
+ struct hostent * server = gethostbyname(host);
162
+ if (server == NULL) {
163
+ fprintf(stderr, "Cannot resolve host '%s'\n", host);
164
+ return nullptr;
165
+ }
166
+ memcpy(&addr.sin_addr.s_addr, server->h_addr, server->h_length);
167
+ if (connect(sock_ptr->fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
168
+ return nullptr;
169
+ }
170
+ return sock_ptr;
171
+ }
172
+
173
+ static std::shared_ptr<socket_t> socket_accept(sockfd_t srv_sockfd) {
174
+ auto client_socket_fd = accept(srv_sockfd, NULL, NULL);
175
+ auto client_socket = make_socket(client_socket_fd);
176
+ if (client_socket == nullptr) {
177
+ return nullptr;
178
+ }
179
+ if (!set_no_delay(client_socket_fd)) {
180
+ fprintf(stderr, "Failed to set TCP_NODELAY\n");
181
+ return nullptr;
182
+ }
183
+ return client_socket;
184
+ }
185
+
186
+ static std::shared_ptr<socket_t> create_server_socket(const char * host, int port) {
187
+ auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
188
+ auto sock = make_socket(sockfd);
189
+ if (sock == nullptr) {
190
+ return nullptr;
191
+ }
192
+ if (!set_reuse_addr(sockfd)) {
193
+ fprintf(stderr, "Failed to set SO_REUSEADDR\n");
194
+ return nullptr;
195
+ }
196
+ struct sockaddr_in serv_addr;
197
+ serv_addr.sin_family = AF_INET;
198
+ serv_addr.sin_addr.s_addr = inet_addr(host);
199
+ serv_addr.sin_port = htons(port);
200
+
201
+ if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
202
+ return nullptr;
203
+ }
204
+ if (listen(sockfd, 1) < 0) {
205
+ return nullptr;
206
+ }
207
+ return sock;
208
+ }
209
+
210
+ static bool send_data(sockfd_t sockfd, const void * data, size_t size) {
211
+ size_t bytes_sent = 0;
212
+ while (bytes_sent < size) {
213
+ ssize_t n = send(sockfd, (const char *)data + bytes_sent, size - bytes_sent, 0);
214
+ if (n < 0) {
215
+ return false;
216
+ }
217
+ bytes_sent += n;
218
+ }
219
+ return true;
220
+ }
221
+
222
+ static bool recv_data(sockfd_t sockfd, void * data, size_t size) {
223
+ size_t bytes_recv = 0;
224
+ while (bytes_recv < size) {
225
+ ssize_t n = recv(sockfd, (char *)data + bytes_recv, size - bytes_recv, 0);
226
+ if (n <= 0) {
227
+ return false;
228
+ }
229
+ bytes_recv += n;
230
+ }
231
+ return true;
232
+ }
233
+
234
+ static bool parse_endpoint(const char * endpoint, std::string & host, int & port) {
235
+ std::string str(endpoint);
236
+ size_t pos = str.find(':');
237
+ if (pos == std::string::npos) {
238
+ return false;
239
+ }
240
+ host = str.substr(0, pos);
241
+ port = std::stoi(str.substr(pos + 1));
242
+ return true;
243
+ }
244
+
245
+ // RPC request : | rpc_cmd (1 byte) | request_size (8 bytes) | request_data (request_size bytes) |
246
+ // RPC response: | response_size (8 bytes) | response_data (response_size bytes) |
247
+ static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
248
+ uint8_t cmd_byte = cmd;
249
+ if (!send_data(sock->fd, &cmd_byte, sizeof(cmd_byte))) {
250
+ return false;
251
+ }
252
+ uint64_t input_size = input.size();
253
+ if (!send_data(sock->fd, &input_size, sizeof(input_size))) {
254
+ return false;
255
+ }
256
+ if (!send_data(sock->fd, input.data(), input.size())) {
257
+ return false;
258
+ }
259
+ uint64_t output_size;
260
+ if (!recv_data(sock->fd, &output_size, sizeof(output_size))) {
261
+ return false;
262
+ }
263
+ if (output_size == 0) {
264
+ output.clear();
265
+ return true;
266
+ }
267
+ output.resize(output_size);
268
+ if (!recv_data(sock->fd, output.data(), output_size)) {
269
+ return false;
270
+ }
271
+ return true;
272
+ }
273
+
274
+ // RPC client-side implementation
275
+
276
+ GGML_CALL static const char * ggml_backend_rpc_buffer_get_name(ggml_backend_buffer_t buffer) {
277
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
278
+ return ctx->name.c_str();
279
+ }
280
+
281
+ GGML_CALL static void ggml_backend_rpc_buffer_free_buffer(ggml_backend_buffer_t buffer) {
282
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
283
+ // input serialization format: | remote_ptr (8 bytes) |
284
+ std::vector<uint8_t> input(sizeof(uint64_t), 0);
285
+ uint64_t remote_ptr = ctx->remote_ptr;
286
+ memcpy(input.data(), &remote_ptr, sizeof(remote_ptr));
287
+ std::vector<uint8_t> output;
288
+ bool status = send_rpc_cmd(ctx->sock, FREE_BUFFER, input, output);
289
+ GGML_ASSERT(status);
290
+ GGML_ASSERT(output.empty());
291
+ delete ctx;
292
+ }
293
+
294
+ GGML_CALL static void * ggml_backend_rpc_buffer_get_base(ggml_backend_buffer_t buffer) {
295
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
296
+ if (ctx->base_cache.find(buffer) != ctx->base_cache.end()) {
297
+ return ctx->base_cache[buffer];
298
+ }
299
+ // input serialization format: | remote_ptr (8 bytes) |
300
+ std::vector<uint8_t> input(sizeof(uint64_t), 0);
301
+ uint64_t remote_ptr = ctx->remote_ptr;
302
+ memcpy(input.data(), &remote_ptr, sizeof(remote_ptr));
303
+ std::vector<uint8_t> output;
304
+ bool status = send_rpc_cmd(ctx->sock, BUFFER_GET_BASE, input, output);
305
+ GGML_ASSERT(status);
306
+ GGML_ASSERT(output.size() == sizeof(uint64_t));
307
+ // output serialization format: | base_ptr (8 bytes) |
308
+ uint64_t base_ptr;
309
+ memcpy(&base_ptr, output.data(), sizeof(base_ptr));
310
+ void * base = reinterpret_cast<void *>(base_ptr);
311
+ ctx->base_cache[buffer] = base;
312
+ return base;
313
+ }
314
+
315
+ static rpc_tensor serialize_tensor(const ggml_tensor * tensor) {
316
+ rpc_tensor result;
317
+ result.id = reinterpret_cast<uint64_t>(tensor);
318
+ result.type = tensor->type;
319
+ if (tensor->buffer) {
320
+ ggml_backend_buffer_t buffer = tensor->buffer;
321
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
322
+ result.buffer = ctx->remote_ptr;
323
+ } else {
324
+ result.buffer = 0;
325
+ }
326
+ for (uint32_t i = 0; i < GGML_MAX_DIMS; i++) {
327
+ result.ne[i] = tensor->ne[i];
328
+ result.nb[i] = tensor->nb[i];
329
+ }
330
+ result.op = tensor->op;
331
+ for (uint32_t i = 0; i < GGML_MAX_OP_PARAMS / sizeof(int32_t); i++) {
332
+ result.op_params[i] = tensor->op_params[i];
333
+ }
334
+ result.flags = tensor->flags;
335
+ for (uint32_t i = 0; i < GGML_MAX_SRC; i++) {
336
+ result.src[i] = reinterpret_cast<uint64_t>(tensor->src[i]);
337
+ }
338
+ result.view_src = reinterpret_cast<uint64_t>(tensor->view_src);
339
+ result.view_offs = tensor->view_offs;
340
+ result.data = reinterpret_cast<uint64_t>(tensor->data);
341
+ snprintf(result.name, GGML_MAX_NAME, "%s", tensor->name);
342
+ return result;
343
+ }
344
+
345
+ GGML_CALL static void ggml_backend_rpc_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
346
+ UNUSED(buffer);
347
+ if (ggml_is_quantized(tensor->type)) {
348
+ // TODO: this check is due to MATRIX_ROW_PADDING in CUDA and should be generalized
349
+ GGML_ASSERT(tensor->ne[0] % 512 == 0 && "unsupported quantized tensor");
350
+ }
351
+ }
352
+
353
+ GGML_CALL static void ggml_backend_rpc_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
354
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
355
+ // input serialization format: | rpc_tensor | offset (8 bytes) | data (size bytes) |
356
+ size_t input_size = sizeof(rpc_tensor) + sizeof(uint64_t) + size;
357
+ std::vector<uint8_t> input(input_size, 0);
358
+ rpc_tensor rpc_tensor = serialize_tensor(tensor);
359
+ memcpy(input.data(), &rpc_tensor, sizeof(rpc_tensor));
360
+ memcpy(input.data() + sizeof(rpc_tensor), &offset, sizeof(offset));
361
+ memcpy(input.data() + sizeof(rpc_tensor) + sizeof(offset), data, size);
362
+ std::vector<uint8_t> output;
363
+ bool status = send_rpc_cmd(ctx->sock, SET_TENSOR, input, output);
364
+ GGML_ASSERT(status);
365
+ }
366
+
367
+ GGML_CALL static void ggml_backend_rpc_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
368
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
369
+ // input serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) |
370
+ int input_size = sizeof(rpc_tensor) + 2*sizeof(uint64_t);
371
+ std::vector<uint8_t> input(input_size, 0);
372
+ rpc_tensor rpc_tensor = serialize_tensor(tensor);
373
+ memcpy(input.data(), &rpc_tensor, sizeof(rpc_tensor));
374
+ memcpy(input.data() + sizeof(rpc_tensor), &offset, sizeof(offset));
375
+ memcpy(input.data() + sizeof(rpc_tensor) + sizeof(offset), &size, sizeof(size));
376
+ std::vector<uint8_t> output;
377
+ bool status = send_rpc_cmd(ctx->sock, GET_TENSOR, input, output);
378
+ GGML_ASSERT(status);
379
+ GGML_ASSERT(output.size() == size);
380
+ // output serialization format: | data (size bytes) |
381
+ memcpy(data, output.data(), size);
382
+ }
383
+
384
+ GGML_CALL static bool ggml_backend_rpc_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
385
+ // check if src and dst are on the same server
386
+ ggml_backend_buffer_t src_buffer = src->buffer;
387
+ ggml_backend_rpc_buffer_context * src_ctx = (ggml_backend_rpc_buffer_context *)src_buffer->context;
388
+ ggml_backend_buffer_t dst_buffer = dst->buffer;
389
+ ggml_backend_rpc_buffer_context * dst_ctx = (ggml_backend_rpc_buffer_context *)dst_buffer->context;
390
+ if (src_ctx->sock != dst_ctx->sock) {
391
+ return false;
392
+ }
393
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
394
+ // input serialization format: | rpc_tensor src | rpc_tensor dst |
395
+ int input_size = 2*sizeof(rpc_tensor);
396
+ std::vector<uint8_t> input(input_size, 0);
397
+ rpc_tensor rpc_src = serialize_tensor(src);
398
+ rpc_tensor rpc_dst = serialize_tensor(dst);
399
+ memcpy(input.data(), &rpc_src, sizeof(rpc_src));
400
+ memcpy(input.data() + sizeof(rpc_src), &rpc_dst, sizeof(rpc_dst));
401
+ std::vector<uint8_t> output;
402
+ bool status = send_rpc_cmd(ctx->sock, COPY_TENSOR, input, output);
403
+ GGML_ASSERT(status);
404
+ // output serialization format: | result (1 byte) |
405
+ GGML_ASSERT(output.size() == 1);
406
+ return output[0];
407
+ }
408
+
409
+ GGML_CALL static void ggml_backend_rpc_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
410
+ ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context;
411
+ // serialization format: | bufptr (8 bytes) | value (1 byte) |
412
+ int input_size = sizeof(uint64_t) + sizeof(uint8_t);
413
+ std::vector<uint8_t> input(input_size, 0);
414
+ memcpy(input.data(), &ctx->remote_ptr, sizeof(ctx->remote_ptr));
415
+ memcpy(input.data() + sizeof(ctx->remote_ptr), &value, sizeof(value));
416
+ std::vector<uint8_t> output;
417
+ bool status = send_rpc_cmd(ctx->sock, BUFFER_CLEAR, input, output);
418
+ GGML_ASSERT(status);
419
+ }
420
+
421
+ static ggml_backend_buffer_i ggml_backend_rpc_buffer_interface = {
422
+ /* .get_name = */ ggml_backend_rpc_buffer_get_name,
423
+ /* .free_buffer = */ ggml_backend_rpc_buffer_free_buffer,
424
+ /* .get_base = */ ggml_backend_rpc_buffer_get_base,
425
+ /* .init_tensor = */ ggml_backend_rpc_buffer_init_tensor,
426
+ /* .set_tensor = */ ggml_backend_rpc_buffer_set_tensor,
427
+ /* .get_tensor = */ ggml_backend_rpc_buffer_get_tensor,
428
+ /* .cpy_tensor = */ ggml_backend_rpc_buffer_cpy_tensor,
429
+ /* .clear = */ ggml_backend_rpc_buffer_clear,
430
+ /* .reset = */ NULL,
431
+ };
432
+
433
+ GGML_CALL static const char * ggml_backend_rpc_buffer_type_name(ggml_backend_buffer_type_t buft) {
434
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context;
435
+ return buft_ctx->name.c_str();
436
+ }
437
+
438
+ GGML_CALL static ggml_backend_buffer_t ggml_backend_rpc_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
439
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context;
440
+ // input serialization format: | size (8 bytes) |
441
+ int input_size = sizeof(uint64_t);
442
+ std::vector<uint8_t> input(input_size, 0);
443
+ memcpy(input.data(), &size, sizeof(size));
444
+ std::vector<uint8_t> output;
445
+ bool status = send_rpc_cmd(buft_ctx->sock, ALLOC_BUFFER, input, output);
446
+ GGML_ASSERT(status);
447
+ GGML_ASSERT(output.size() == 2*sizeof(uint64_t));
448
+ // output serialization format: | remote_ptr (8 bytes) | remote_size (8 bytes) |
449
+ uint64_t remote_ptr;
450
+ memcpy(&remote_ptr, output.data(), sizeof(remote_ptr));
451
+ size_t remote_size;
452
+ memcpy(&remote_size, output.data() + sizeof(uint64_t), sizeof(remote_size));
453
+ if (remote_ptr != 0) {
454
+ ggml_backend_buffer_t buffer = ggml_backend_buffer_init(buft,
455
+ ggml_backend_rpc_buffer_interface,
456
+ new ggml_backend_rpc_buffer_context{buft_ctx->sock, {}, remote_ptr, "RPC"},
457
+ remote_size);
458
+ return buffer;
459
+ } else {
460
+ return nullptr;
461
+ }
462
+ }
463
+
464
+ static size_t get_alignment(const std::shared_ptr<socket_t> & sock) {
465
+ // input serialization format: | 0 bytes |
466
+ std::vector<uint8_t> input;
467
+ std::vector<uint8_t> output;
468
+ bool status = send_rpc_cmd(sock, GET_ALIGNMENT, input, output);
469
+ GGML_ASSERT(status);
470
+ GGML_ASSERT(output.size() == sizeof(uint64_t));
471
+ // output serialization format: | alignment (8 bytes) |
472
+ uint64_t alignment;
473
+ memcpy(&alignment, output.data(), sizeof(alignment));
474
+ return alignment;
475
+ }
476
+
477
+ GGML_CALL static size_t ggml_backend_rpc_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
478
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context;
479
+ return buft_ctx->alignment;
480
+ }
481
+
482
+ static size_t get_max_size(const std::shared_ptr<socket_t> & sock) {
483
+ // input serialization format: | 0 bytes |
484
+ std::vector<uint8_t> input;
485
+ std::vector<uint8_t> output;
486
+ bool status = send_rpc_cmd(sock, GET_MAX_SIZE, input, output);
487
+ GGML_ASSERT(status);
488
+ GGML_ASSERT(output.size() == sizeof(uint64_t));
489
+ // output serialization format: | max_size (8 bytes) |
490
+ uint64_t max_size;
491
+ memcpy(&max_size, output.data(), sizeof(max_size));
492
+ return max_size;
493
+ }
494
+
495
+ GGML_CALL static size_t ggml_backend_rpc_get_max_size(ggml_backend_buffer_type_t buft) {
496
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context;
497
+ return buft_ctx->max_size;
498
+ }
499
+
500
+ GGML_CALL static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
501
+ UNUSED(buft);
502
+ return ggml_nbytes(tensor);
503
+ }
504
+
505
+ GGML_CALL static bool ggml_backend_rpc_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
506
+ if (!ggml_backend_is_rpc(backend)) {
507
+ return false;
508
+ }
509
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context;
510
+ ggml_backend_rpc_context * rpc_ctx = (ggml_backend_rpc_context *)backend->context;
511
+ return buft_ctx->sock == rpc_ctx->sock;
512
+ }
513
+
514
+ static ggml_backend_buffer_type_i ggml_backend_rpc_buffer_type_interface = {
515
+ /* .get_name = */ ggml_backend_rpc_buffer_type_name,
516
+ /* .alloc_buffer = */ ggml_backend_rpc_buffer_type_alloc_buffer,
517
+ /* .get_alignment = */ ggml_backend_rpc_buffer_type_get_alignment,
518
+ /* .get_max_size = */ ggml_backend_rpc_get_max_size,
519
+ /* .get_alloc_size = */ ggml_backend_rpc_buffer_type_get_alloc_size,
520
+ /* .supports_backend = */ ggml_backend_rpc_buffer_type_supports_backend,
521
+ /* .is_host = */ NULL,
522
+ };
523
+
524
+
525
+ GGML_CALL static const char * ggml_backend_rpc_name(ggml_backend_t backend) {
526
+ ggml_backend_rpc_context * rpc_ctx = (ggml_backend_rpc_context *)backend->context;
527
+
528
+ return rpc_ctx->name.c_str();
529
+ }
530
+
531
+ GGML_CALL static void ggml_backend_rpc_free(ggml_backend_t backend) {
532
+ ggml_backend_rpc_context * rpc_ctx = (ggml_backend_rpc_context *)backend->context;
533
+ ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)rpc_ctx->buft->context;
534
+ delete buft_ctx;
535
+ delete rpc_ctx->buft;
536
+ delete rpc_ctx;
537
+ delete backend;
538
+ }
539
+
540
+ GGML_CALL static ggml_backend_buffer_type_t ggml_backend_rpc_get_default_buffer_type(ggml_backend_t backend) {
541
+ ggml_backend_rpc_context * ctx = (ggml_backend_rpc_context *)backend->context;
542
+ return ctx->buft;
543
+ }
544
+
545
+ GGML_CALL static void ggml_backend_rpc_synchronize(ggml_backend_t backend) {
546
+ UNUSED(backend);
547
+ // this is no-op because we don't have any async operations
548
+ }
549
+
550
+ static void add_tensor(ggml_tensor * tensor, std::vector<rpc_tensor> & tensors, std::unordered_set<ggml_tensor*> & visited) {
551
+ if (tensor == nullptr) {
552
+ return;
553
+ }
554
+ if (visited.find(tensor) != visited.end()) {
555
+ return;
556
+ }
557
+ visited.insert(tensor);
558
+ for (int i = 0; i < GGML_MAX_SRC; i++) {
559
+ add_tensor(tensor->src[i], tensors, visited);
560
+ }
561
+ add_tensor(tensor->view_src, tensors, visited);
562
+ tensors.push_back(serialize_tensor(tensor));
563
+ }
564
+
565
+ static void serialize_graph(const ggml_cgraph * cgraph, std::vector<uint8_t> & output) {
566
+ uint32_t n_nodes = cgraph->n_nodes;
567
+ std::vector<rpc_tensor> tensors;
568
+ std::unordered_set<ggml_tensor*> visited;
569
+ for (uint32_t i = 0; i < n_nodes; i++) {
570
+ add_tensor(cgraph->nodes[i], tensors, visited);
571
+ }
572
+ // serialization format:
573
+ // | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) |
574
+ uint32_t n_tensors = tensors.size();
575
+ int output_size = sizeof(uint32_t) + n_nodes * sizeof(uint64_t) + sizeof(uint32_t) + n_tensors * sizeof(rpc_tensor);
576
+ output.resize(output_size, 0);
577
+ memcpy(output.data(), &n_nodes, sizeof(n_nodes));
578
+ uint64_t * out_nodes = (uint64_t *)(output.data() + sizeof(n_nodes));
579
+ for (uint32_t i = 0; i < n_nodes; i++) {
580
+ out_nodes[i] = reinterpret_cast<uint64_t>(cgraph->nodes[i]);
581
+ }
582
+ uint32_t * out_ntensors = (uint32_t *)(output.data() + sizeof(n_nodes) + n_nodes * sizeof(uint64_t));
583
+ *out_ntensors = n_tensors;
584
+ rpc_tensor * out_tensors = (rpc_tensor *)(output.data() + sizeof(n_nodes) + n_nodes * sizeof(uint64_t) + sizeof(uint32_t));
585
+ memcpy(out_tensors, tensors.data(), n_tensors * sizeof(rpc_tensor));
586
+ }
587
+
588
+ GGML_CALL static enum ggml_status ggml_backend_rpc_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
589
+ ggml_backend_rpc_context * rpc_ctx = (ggml_backend_rpc_context *)backend->context;
590
+ std::vector<uint8_t> input;
591
+ serialize_graph(cgraph, input);
592
+ std::vector<uint8_t> output;
593
+ bool status = send_rpc_cmd(rpc_ctx->sock, GRAPH_COMPUTE, input, output);
594
+ GGML_ASSERT(status);
595
+ GGML_ASSERT(output.size() == 1);
596
+ return (enum ggml_status)output[0];
597
+ }
598
+
599
+ GGML_CALL static bool ggml_backend_rpc_supports_op(ggml_backend_t backend, const ggml_tensor * op) {
600
+ UNUSED(backend);
601
+ UNUSED(op);
602
+ GGML_ASSERT(false && "not implemented");
603
+ return false;
604
+ }
605
+
606
+ static ggml_backend_i ggml_backend_rpc_interface = {
607
+ /* .get_name = */ ggml_backend_rpc_name,
608
+ /* .free = */ ggml_backend_rpc_free,
609
+ /* .get_default_buffer_type = */ ggml_backend_rpc_get_default_buffer_type,
610
+ /* .set_tensor_async = */ NULL,
611
+ /* .get_tensor_async = */ NULL,
612
+ /* .cpy_tensor_async = */ NULL,
613
+ /* .synchronize = */ ggml_backend_rpc_synchronize,
614
+ /* .graph_plan_create = */ NULL,
615
+ /* .graph_plan_free = */ NULL,
616
+ /* .graph_plan_compute = */ NULL,
617
+ /* .graph_compute = */ ggml_backend_rpc_graph_compute,
618
+ /* .supports_op = */ ggml_backend_rpc_supports_op,
619
+ /* .offload_op = */ NULL,
620
+ /* .event_new = */ NULL,
621
+ /* .event_free = */ NULL,
622
+ /* .event_record = */ NULL,
623
+ /* .event_wait = */ NULL,
624
+ /* .event_synchronize = */ NULL,
625
+ };
626
+
627
+ static std::unordered_map<std::string, ggml_backend_t> instances;
628
+
629
+ GGML_API GGML_CALL ggml_backend_buffer_type_t ggml_backend_rpc_buffer_type(const char * endpoint) {
630
+ ggml_backend_t backend = ggml_backend_rpc_init(endpoint);
631
+ return backend != nullptr ? ggml_backend_rpc_get_default_buffer_type(backend) : nullptr;
632
+ }
633
+
634
+ GGML_CALL ggml_backend_t ggml_backend_rpc_init(const char * endpoint) {
635
+ std::string endpoint_str(endpoint);
636
+ if (instances.find(endpoint_str) != instances.end()) {
637
+ return instances[endpoint_str];
638
+ }
639
+ #ifdef _WIN32
640
+ {
641
+ WSADATA wsaData;
642
+ int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
643
+ if (res != 0) {
644
+ return nullptr;
645
+ }
646
+ }
647
+ #endif
648
+ fprintf(stderr, "Connecting to %s\n", endpoint);
649
+ std::string host;
650
+ int port;
651
+ if (!parse_endpoint(endpoint, host, port)) {
652
+ return nullptr;
653
+ }
654
+ auto sock = socket_connect(host.c_str(), port);
655
+ if (sock == nullptr) {
656
+ return nullptr;
657
+ }
658
+ size_t alignment = get_alignment(sock);
659
+ size_t max_size = get_max_size(sock);
660
+ ggml_backend_rpc_buffer_type_context * buft_ctx = new ggml_backend_rpc_buffer_type_context {
661
+ /* .sock = */ sock,
662
+ /* .name = */ "RPC" + std::to_string(sock->fd),
663
+ /* .alignment = */ alignment,
664
+ /* .max_size = */ max_size
665
+ };
666
+
667
+ ggml_backend_buffer_type_t buft = new ggml_backend_buffer_type {
668
+ /* .iface = */ ggml_backend_rpc_buffer_type_interface,
669
+ /* .context = */ buft_ctx
670
+ };
671
+
672
+ ggml_backend_rpc_context * ctx = new ggml_backend_rpc_context {
673
+ /* .endpoint = */ endpoint,
674
+ /* .name = */ "RPC" + std::to_string(sock->fd),
675
+ /* .sock = */ sock,
676
+ /* .buft = */ buft
677
+ };
678
+
679
+ instances[endpoint] = new ggml_backend {
680
+ /* .guid = */ ggml_backend_rpc_guid(),
681
+ /* .interface = */ ggml_backend_rpc_interface,
682
+ /* .context = */ ctx
683
+ };
684
+
685
+ return instances[endpoint];
686
+ }
687
+
688
+ GGML_API GGML_CALL bool ggml_backend_is_rpc(ggml_backend_t backend) {
689
+ return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_rpc_guid());
690
+ }
691
+
692
+ static void get_device_memory(const std::shared_ptr<socket_t> & sock, size_t * free, size_t * total) {
693
+ // input serialization format: | 0 bytes |
694
+ std::vector<uint8_t> input;
695
+ std::vector<uint8_t> output;
696
+ bool status = send_rpc_cmd(sock, GET_DEVICE_MEMORY, input, output);
697
+ GGML_ASSERT(status);
698
+ GGML_ASSERT(output.size() == 2*sizeof(uint64_t));
699
+ // output serialization format: | free (8 bytes) | total (8 bytes) |
700
+ uint64_t free_mem;
701
+ memcpy(&free_mem, output.data(), sizeof(free_mem));
702
+ uint64_t total_mem;
703
+ memcpy(&total_mem, output.data() + sizeof(uint64_t), sizeof(total_mem));
704
+ *free = free_mem;
705
+ *total = total_mem;
706
+ }
707
+
708
+ GGML_API GGML_CALL void ggml_backend_rpc_get_device_memory(const char * endpoint, size_t * free, size_t * total) {
709
+ ggml_backend_t backend = ggml_backend_rpc_init(endpoint);
710
+ if (backend == nullptr) {
711
+ *free = 0;
712
+ *total = 0;
713
+ return;
714
+ }
715
+ ggml_backend_rpc_context * ctx = (ggml_backend_rpc_context *)backend->context;
716
+ get_device_memory(ctx->sock, free, total);
717
+ }
718
+
719
+ // RPC server-side implementation
720
+
721
+ class rpc_server {
722
+ public:
723
+ rpc_server(ggml_backend_t backend) : backend(backend) {}
724
+ ~rpc_server();
725
+
726
+ bool alloc_buffer(const std::vector<uint8_t> & input, std::vector<uint8_t> & output);
727
+ void get_alignment(std::vector<uint8_t> & output);
728
+ void get_max_size(std::vector<uint8_t> & output);
729
+ bool buffer_get_base(const std::vector<uint8_t> & input, std::vector<uint8_t> & output);
730
+ bool free_buffer(const std::vector<uint8_t> & input);
731
+ bool buffer_clear(const std::vector<uint8_t> & input);
732
+ bool set_tensor(const std::vector<uint8_t> & input);
733
+ bool get_tensor(const std::vector<uint8_t> & input, std::vector<uint8_t> & output);
734
+ bool copy_tensor(const std::vector<uint8_t> & input, std::vector<uint8_t> & output);
735
+ bool graph_compute(const std::vector<uint8_t> & input, std::vector<uint8_t> & output);
736
+
737
+ private:
738
+ ggml_tensor * deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor);
739
+ ggml_tensor * create_node(uint64_t id,
740
+ struct ggml_context * ctx,
741
+ const std::unordered_map<uint64_t, const rpc_tensor*> & tensor_ptrs,
742
+ std::unordered_map<uint64_t, struct ggml_tensor*> & tensor_map);
743
+
744
+
745
+ ggml_backend_t backend;
746
+ std::unordered_set<ggml_backend_buffer_t> buffers;
747
+ };
748
+
749
+ bool rpc_server::alloc_buffer(const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
750
+ // input serialization format: | size (8 bytes) |
751
+ if (input.size() != sizeof(uint64_t)) {
752
+ return false;
753
+ }
754
+ uint64_t size;
755
+ memcpy(&size, input.data(), sizeof(size));
756
+ ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backend);
757
+ ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, size);
758
+ uint64_t remote_ptr = 0;
759
+ uint64_t remote_size = 0;
760
+ if (buffer != nullptr) {
761
+ remote_ptr = reinterpret_cast<uint64_t>(buffer);
762
+ remote_size = buffer->size;
763
+ GGML_PRINT_DEBUG("[%s] size: %" PRIu64 " -> remote_ptr: %" PRIx64 ", remote_size: %" PRIu64 "\n", __func__, size, remote_ptr, remote_size);
764
+ buffers.insert(buffer);
765
+ } else {
766
+ GGML_PRINT_DEBUG("[%s] size: %" PRIu64 " -> failed\n", __func__, size);
767
+ }
768
+ // output serialization format: | remote_ptr (8 bytes) | remote_size (8 bytes) |
769
+ output.resize(2*sizeof(uint64_t), 0);
770
+ memcpy(output.data(), &remote_ptr, sizeof(remote_ptr));
771
+ memcpy(output.data() + sizeof(uint64_t), &remote_size, sizeof(remote_size));
772
+ return true;
773
+ }
774
+
775
+ void rpc_server::get_alignment(std::vector<uint8_t> & output) {
776
+ ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backend);
777
+ size_t alignment = ggml_backend_buft_get_alignment(buft);
778
+ GGML_PRINT_DEBUG("[%s] alignment: %lu\n", __func__, alignment);
779
+ // output serialization format: | alignment (8 bytes) |
780
+ output.resize(sizeof(uint64_t), 0);
781
+ memcpy(output.data(), &alignment, sizeof(alignment));
782
+ }
783
+
784
+ void rpc_server::get_max_size(std::vector<uint8_t> & output) {
785
+ ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backend);
786
+ size_t max_size = ggml_backend_buft_get_max_size(buft);
787
+ GGML_PRINT_DEBUG("[%s] max_size: %lu\n", __func__, max_size);
788
+ // output serialization format: | max_size (8 bytes) |
789
+ output.resize(sizeof(uint64_t), 0);
790
+ memcpy(output.data(), &max_size, sizeof(max_size));
791
+ }
792
+
793
+ bool rpc_server::buffer_get_base(const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
794
+ // input serialization format: | remote_ptr (8 bytes) |
795
+ if (input.size() != sizeof(uint64_t)) {
796
+ return false;
797
+ }
798
+ uint64_t remote_ptr;
799
+ memcpy(&remote_ptr, input.data(), sizeof(remote_ptr));
800
+ GGML_PRINT_DEBUG("[%s] remote_ptr: %" PRIx64 "\n", __func__, remote_ptr);
801
+ ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(remote_ptr);
802
+ if (buffers.find(buffer) == buffers.end()) {
803
+ GGML_PRINT_DEBUG("[%s] buffer not found\n", __func__);
804
+ return false;
805
+ }
806
+ void * base = ggml_backend_buffer_get_base(buffer);
807
+ // output serialization format: | base_ptr (8 bytes) |
808
+ uint64_t base_ptr = reinterpret_cast<uint64_t>(base);
809
+ output.resize(sizeof(uint64_t), 0);
810
+ memcpy(output.data(), &base_ptr, sizeof(base_ptr));
811
+ return true;
812
+ }
813
+
814
+ bool rpc_server::free_buffer(const std::vector<uint8_t> & input) {
815
+ // input serialization format: | remote_ptr (8 bytes) |
816
+ if (input.size() != sizeof(uint64_t)) {
817
+ return false;
818
+ }
819
+ uint64_t remote_ptr;
820
+ memcpy(&remote_ptr, input.data(), sizeof(remote_ptr));
821
+ GGML_PRINT_DEBUG("[%s] remote_ptr: %" PRIx64 "\n", __func__, remote_ptr);
822
+ ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(remote_ptr);
823
+ if (buffers.find(buffer) == buffers.end()) {
824
+ GGML_PRINT_DEBUG("[%s] buffer not found\n", __func__);
825
+ return false;
826
+ }
827
+ ggml_backend_buffer_free(buffer);
828
+ buffers.erase(buffer);
829
+ return true;
830
+ }
831
+
832
+ bool rpc_server::buffer_clear(const std::vector<uint8_t> & input) {
833
+ // input serialization format: | remote_ptr (8 bytes) | value (1 byte) |
834
+ if (input.size() != sizeof(uint64_t) + sizeof(uint8_t)) {
835
+ return false;
836
+ }
837
+ uint64_t remote_ptr;
838
+ memcpy(&remote_ptr, input.data(), sizeof(remote_ptr));
839
+ uint8_t value;
840
+ memcpy(&value, input.data() + sizeof(uint64_t), sizeof(value));
841
+ GGML_PRINT_DEBUG("[%s] remote_ptr: %" PRIx64 ", value: %u\n", __func__, remote_ptr, value);
842
+ ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(remote_ptr);
843
+ if (buffers.find(buffer) == buffers.end()) {
844
+ GGML_PRINT_DEBUG("[%s] buffer not found\n", __func__);
845
+ return false;
846
+ }
847
+ ggml_backend_buffer_clear(buffer, value);
848
+ return true;
849
+ }
850
+
851
+ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor) {
852
+ ggml_tensor * result = ggml_new_tensor_4d(ctx, (ggml_type) tensor->type,
853
+ tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
854
+ for (uint32_t i = 0; i < GGML_MAX_DIMS; i++) {
855
+ result->nb[i] = tensor->nb[i];
856
+ }
857
+ result->buffer = reinterpret_cast<ggml_backend_buffer_t>(tensor->buffer);
858
+ if (result->buffer && buffers.find(result->buffer) == buffers.end()) {
859
+ return nullptr;
860
+ }
861
+ result->op = (ggml_op) tensor->op;
862
+ for (uint32_t i = 0; i < GGML_MAX_OP_PARAMS / sizeof(int32_t); i++) {
863
+ result->op_params[i] = tensor->op_params[i];
864
+ }
865
+ result->flags = tensor->flags;
866
+ result->data = reinterpret_cast<void *>(tensor->data);
867
+ ggml_set_name(result, tensor->name);
868
+ return result;
869
+ }
870
+
871
+
872
+ bool rpc_server::set_tensor(const std::vector<uint8_t> & input) {
873
+ // serialization format: | rpc_tensor | offset (8 bytes) | data (size bytes) |
874
+ if (input.size() < sizeof(rpc_tensor) + sizeof(uint64_t)) {
875
+ return false;
876
+ }
877
+ const rpc_tensor * in_tensor = (const rpc_tensor *)input.data();
878
+ uint64_t offset;
879
+ memcpy(&offset, input.data() + sizeof(rpc_tensor), sizeof(offset));
880
+ size_t size = input.size() - sizeof(rpc_tensor) - sizeof(offset);
881
+
882
+ struct ggml_init_params params {
883
+ /*.mem_size =*/ ggml_tensor_overhead(),
884
+ /*.mem_buffer =*/ NULL,
885
+ /*.no_alloc =*/ true,
886
+ };
887
+ struct ggml_context * ctx = ggml_init(params);
888
+ ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor);
889
+ if (tensor == nullptr) {
890
+ GGML_PRINT_DEBUG("[%s] error deserializing tensor\n", __func__);
891
+ ggml_free(ctx);
892
+ return false;
893
+ }
894
+ GGML_PRINT_DEBUG("[%s] buffer: %p, data: %p, offset: %" PRIu64 ", size: %zu\n", __func__, (void*)tensor->buffer, tensor->data, offset, size);
895
+ const void * data = input.data() + sizeof(rpc_tensor) + sizeof(offset);
896
+ ggml_backend_tensor_set(tensor, data, offset, size);
897
+ ggml_free(ctx);
898
+ return true;
899
+ }
900
+
901
+ bool rpc_server::get_tensor(const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
902
+ // serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) |
903
+ if (input.size() != sizeof(rpc_tensor) + 2*sizeof(uint64_t)) {
904
+ return false;
905
+ }
906
+ const rpc_tensor * in_tensor = (const rpc_tensor *)input.data();
907
+ uint64_t offset;
908
+ memcpy(&offset, input.data() + sizeof(rpc_tensor), sizeof(offset));
909
+ uint64_t size;
910
+ memcpy(&size, input.data() + sizeof(rpc_tensor) + sizeof(offset), sizeof(size));
911
+
912
+ struct ggml_init_params params {
913
+ /*.mem_size =*/ ggml_tensor_overhead(),
914
+ /*.mem_buffer =*/ NULL,
915
+ /*.no_alloc =*/ true,
916
+ };
917
+ struct ggml_context * ctx = ggml_init(params);
918
+ ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor);
919
+ if (tensor == nullptr) {
920
+ GGML_PRINT_DEBUG("[%s] error deserializing tensor\n", __func__);
921
+ ggml_free(ctx);
922
+ return false;
923
+ }
924
+ GGML_PRINT_DEBUG("[%s] buffer: %p, data: %p, offset: %" PRIu64 ", size: %" PRIu64 "\n", __func__, (void*)tensor->buffer, tensor->data, offset, size);
925
+ // output serialization format: | data (size bytes) |
926
+ output.resize(size, 0);
927
+ ggml_backend_tensor_get(tensor, output.data(), offset, size);
928
+ ggml_free(ctx);
929
+ return true;
930
+ }
931
+
932
+ bool rpc_server::copy_tensor(const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
933
+ // serialization format: | rpc_tensor src | rpc_tensor dst |
934
+ if (input.size() != 2*sizeof(rpc_tensor)) {
935
+ return false;
936
+ }
937
+ const rpc_tensor * rpc_src = (const rpc_tensor *)input.data();
938
+ const rpc_tensor * rpc_dst = (const rpc_tensor *)(input.data() + sizeof(rpc_src));
939
+
940
+ struct ggml_init_params params {
941
+ /*.mem_size =*/ 2*ggml_tensor_overhead(),
942
+ /*.mem_buffer =*/ NULL,
943
+ /*.no_alloc =*/ true,
944
+ };
945
+ struct ggml_context * ctx = ggml_init(params);
946
+ ggml_tensor * src = deserialize_tensor(ctx, rpc_src);
947
+ ggml_tensor * dst = deserialize_tensor(ctx, rpc_dst);
948
+ if (src == nullptr || dst == nullptr) {
949
+ GGML_PRINT_DEBUG("[%s] error deserializing tensors\n", __func__);
950
+ ggml_free(ctx);
951
+ return false;
952
+ }
953
+ GGML_PRINT_DEBUG("[%s] src->buffer: %p, dst->buffer: %p\n", __func__, (void*)src->buffer, (void*)dst->buffer);
954
+ bool result = ggml_backend_buffer_copy_tensor(src, dst);
955
+ // output serialization format: | result (1 byte) |
956
+ output.resize(1, 0);
957
+ output[0] = result;
958
+ ggml_free(ctx);
959
+ return true;
960
+ }
961
+
962
+ ggml_tensor * rpc_server::create_node(uint64_t id,
963
+ struct ggml_context * ctx,
964
+ const std::unordered_map<uint64_t, const rpc_tensor*> & tensor_ptrs,
965
+ std::unordered_map<uint64_t, struct ggml_tensor*> & tensor_map) {
966
+ if (id == 0) {
967
+ return nullptr;
968
+ }
969
+ if (tensor_map.find(id) != tensor_map.end()) {
970
+ return tensor_map[id];
971
+ }
972
+ const rpc_tensor * tensor = tensor_ptrs.at(id);
973
+ struct ggml_tensor * result = deserialize_tensor(ctx, tensor);
974
+ if (result == nullptr) {
975
+ return nullptr;
976
+ }
977
+ tensor_map[id] = result;
978
+ for (int i = 0; i < GGML_MAX_SRC; i++) {
979
+ result->src[i] = create_node(tensor->src[i], ctx, tensor_ptrs, tensor_map);
980
+ }
981
+ result->view_src = create_node(tensor->view_src, ctx, tensor_ptrs, tensor_map);
982
+ result->view_offs = tensor->view_offs;
983
+ return result;
984
+ }
985
+
986
+ bool rpc_server::graph_compute(const std::vector<uint8_t> & input, std::vector<uint8_t> & output) {
987
+ // serialization format:
988
+ // | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) |
989
+ if (input.size() < sizeof(uint32_t)) {
990
+ return false;
991
+ }
992
+ uint32_t n_nodes;
993
+ memcpy(&n_nodes, input.data(), sizeof(n_nodes));
994
+ if (input.size() < sizeof(uint32_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t)) {
995
+ return false;
996
+ }
997
+ const uint64_t * nodes = (const uint64_t *)(input.data() + sizeof(n_nodes));
998
+ uint32_t n_tensors;
999
+ memcpy(&n_tensors, input.data() + sizeof(n_nodes) + n_nodes*sizeof(uint64_t), sizeof(n_tensors));
1000
+ if (input.size() < sizeof(uint32_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t) + n_tensors*sizeof(rpc_tensor)) {
1001
+ return false;
1002
+ }
1003
+ const rpc_tensor * tensors = (const rpc_tensor *)(input.data() + sizeof(n_nodes) + n_nodes*sizeof(uint64_t) + sizeof(n_tensors));
1004
+ GGML_PRINT_DEBUG("[%s] n_nodes: %u, n_tensors: %u\n", __func__, n_nodes, n_tensors);
1005
+
1006
+ static size_t buf_size = ggml_tensor_overhead()*(n_nodes + n_tensors) + ggml_graph_overhead_custom(n_nodes, false);
1007
+ struct ggml_init_params params = {
1008
+ /*.mem_size =*/ buf_size,
1009
+ /*.mem_buffer =*/ NULL,
1010
+ /*.no_alloc =*/ true,
1011
+ };
1012
+ struct ggml_context * ctx = ggml_init(params);
1013
+ struct ggml_cgraph * graph = ggml_new_graph_custom(ctx, n_nodes, false);
1014
+ graph->n_nodes = n_nodes;
1015
+ std::unordered_map<uint64_t, const rpc_tensor*> tensor_ptrs;
1016
+ for (uint32_t i = 0; i < n_tensors; i++) {
1017
+ tensor_ptrs[tensors[i].id] = &tensors[i];
1018
+ }
1019
+ std::unordered_map<uint64_t, ggml_tensor*> tensor_map;
1020
+ for (uint32_t i = 0; i < n_nodes; i++) {
1021
+ graph->nodes[i] = create_node(nodes[i], ctx, tensor_ptrs, tensor_map);
1022
+ }
1023
+ ggml_status status = ggml_backend_graph_compute(backend, graph);
1024
+ // output serialization format: | status (1 byte) |
1025
+ output.resize(1, 0);
1026
+ output[0] = status;
1027
+ ggml_free(ctx);
1028
+ return true;
1029
+ }
1030
+
1031
+ rpc_server::~rpc_server() {
1032
+ for (auto buffer : buffers) {
1033
+ ggml_backend_buffer_free(buffer);
1034
+ }
1035
+ }
1036
+
1037
+ static void rpc_serve_client(ggml_backend_t backend, sockfd_t sockfd, size_t free_mem, size_t total_mem) {
1038
+ rpc_server server(backend);
1039
+ while (true) {
1040
+ uint8_t cmd;
1041
+ if (!recv_data(sockfd, &cmd, 1)) {
1042
+ break;
1043
+ }
1044
+ std::vector<uint8_t> input;
1045
+ std::vector<uint8_t> output;
1046
+ uint64_t input_size;
1047
+ if (!recv_data(sockfd, &input_size, sizeof(input_size))) {
1048
+ break;
1049
+ }
1050
+ input.resize(input_size);
1051
+ if (!recv_data(sockfd, input.data(), input_size)) {
1052
+ break;
1053
+ }
1054
+ bool ok = true;
1055
+ switch (cmd) {
1056
+ case ALLOC_BUFFER: {
1057
+ ok = server.alloc_buffer(input, output);
1058
+ break;
1059
+ }
1060
+ case GET_ALIGNMENT: {
1061
+ server.get_alignment(output);
1062
+ break;
1063
+ }
1064
+ case GET_MAX_SIZE: {
1065
+ server.get_max_size(output);
1066
+ break;
1067
+ }
1068
+ case BUFFER_GET_BASE: {
1069
+ ok = server.buffer_get_base(input, output);
1070
+ break;
1071
+ }
1072
+ case FREE_BUFFER: {
1073
+ ok = server.free_buffer(input);
1074
+ break;
1075
+ }
1076
+ case BUFFER_CLEAR: {
1077
+ ok = server.buffer_clear(input);
1078
+ break;
1079
+ }
1080
+ case SET_TENSOR: {
1081
+ ok = server.set_tensor(input);
1082
+ break;
1083
+ }
1084
+ case GET_TENSOR: {
1085
+ ok = server.get_tensor(input, output);
1086
+ break;
1087
+ }
1088
+ case COPY_TENSOR: {
1089
+ ok = server.copy_tensor(input, output);
1090
+ break;
1091
+ }
1092
+ case GRAPH_COMPUTE: {
1093
+ ok = server.graph_compute(input, output);
1094
+ break;
1095
+ }
1096
+ case GET_DEVICE_MEMORY: {
1097
+ // output serialization format: | free (8 bytes) | total (8 bytes) |
1098
+ output.resize(2*sizeof(uint64_t), 0);
1099
+ memcpy(output.data(), &free_mem, sizeof(free_mem));
1100
+ memcpy(output.data() + sizeof(uint64_t), &total_mem, sizeof(total_mem));
1101
+ break;
1102
+ }
1103
+ default: {
1104
+ fprintf(stderr, "Unknown command: %d\n", cmd);
1105
+ ok = false;
1106
+ }
1107
+ }
1108
+ if (!ok) {
1109
+ break;
1110
+ }
1111
+ uint64_t output_size = output.size();
1112
+ if (!send_data(sockfd, &output_size, sizeof(output_size))) {
1113
+ break;
1114
+ }
1115
+ if (!send_data(sockfd, output.data(), output_size)) {
1116
+ break;
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ void start_rpc_server(ggml_backend_t backend, const char * endpoint, size_t free_mem, size_t total_mem) {
1122
+ std::string host;
1123
+ int port;
1124
+ if (!parse_endpoint(endpoint, host, port)) {
1125
+ return;
1126
+ }
1127
+ #ifdef _WIN32
1128
+ {
1129
+ WSADATA wsaData;
1130
+ int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
1131
+ if (res != 0) {
1132
+ fprintf(stderr, "WSAStartup failed: %d\n", res);
1133
+ return;
1134
+ }
1135
+ }
1136
+ #endif
1137
+ auto server_socket = create_server_socket(host.c_str(), port);
1138
+ if (server_socket == nullptr) {
1139
+ fprintf(stderr, "Failed to create server socket\n");
1140
+ return;
1141
+ }
1142
+ while (true) {
1143
+ auto client_socket = socket_accept(server_socket->fd);
1144
+ if (client_socket == nullptr) {
1145
+ fprintf(stderr, "Failed to accept client connection\n");
1146
+ return;
1147
+ }
1148
+ printf("Accepted client connection, free_mem=%zu, total_mem=%zu\n", free_mem, total_mem);
1149
+ rpc_serve_client(backend, client_socket->fd, free_mem, total_mem);
1150
+ printf("Client connection closed\n");
1151
+ }
1152
+ #ifdef _WIN32
1153
+ WSACleanup();
1154
+ #endif
1155
+ }