-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllama_rdma_client.cpp
11500 lines (9590 loc) · 435 KB
/
llama_rdma_client.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define LLAMA_API_INTERNAL
#include "llama.h"
#include "unicode.h"
#include "ggml.h"
#include "ggml-alloc.h"
#include "cuda_runtime.h"
#ifdef GGML_USE_CUBLAS
# include "ggml-cuda.h"
#elif defined(GGML_USE_CLBLAST)
# include "ggml-opencl.h"
#endif
// #include "rdma_common.h"
#ifdef GGML_USE_METAL
# include "ggml-metal.h"
#endif
#ifdef GGML_USE_MPI
# include "ggml-mpi.h"
#endif
#ifndef QK_K
# ifdef GGML_QKK_64
# define QK_K 64
# else
# define QK_K 256
# endif
#endif
#ifdef __has_include
#if __has_include(<unistd.h>)
#include <unistd.h>
#if defined(_POSIX_MAPPED_FILES)
#include <sys/mman.h>
#endif
#if defined(_POSIX_MEMLOCK_RANGE)
#include <sys/resource.h>
#endif
#endif
#endif
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <io.h>
#include <stdio.h> // for _fseeki64
#include <direct.h>
#define F_OK 0
#else
#include <libgen.h>
#endif
#include <iostream>
#include <algorithm>
#include <array>
#include <cassert>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <forward_list>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <vector>
#include <ctime>
#if defined(_MSC_VER)
#pragma warning(disable: 4244 4267) // possible loss of data
#endif
#ifdef __GNUC__
#ifdef __MINGW32__
#define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
#else
#define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
#endif
#else
#define LLAMA_ATTRIBUTE_FORMAT(...)
#endif
#define LLAMA_MAX_NODES 4096
void * rdma_idx_vec;
//
// global variables (should be removed after a better design)
//
size_t vram_budget_bytes = 0;
//
// logging
//
LLAMA_ATTRIBUTE_FORMAT(2, 3)
static void llama_log_internal (ggml_log_level level, const char* format, ...);
static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
#define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
#define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
#define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
//
// helpers
//
//=============rdma=====================
#define NUM_QPS 5
static struct rdma_event_channel *cm_event_channel = NULL;
static struct rdma_cm_id *cm_client_id = NULL;
static struct ibv_pd *pd = NULL;
static struct ibv_comp_channel *io_completion_channel = NULL;
static struct ibv_cq *client_cq = NULL;
static struct ibv_qp *client_qp;
/* These are memory buffers related resources */
static struct ibv_mr *client_metadata_mr = NULL,
*client_src_mr = NULL,
*client_dst_mr = NULL,
*server_metadata_mr = NULL;
static struct rdma_buffer_attr client_metadata_attr, server_metadata_attr;
static struct ibv_send_wr client_send_wr, *bad_client_send_wr = NULL;
static struct ibv_recv_wr server_recv_wr, *bad_server_recv_wr = NULL;
static struct ibv_sge client_send_sge, server_recv_sge;
static struct rdma_cm_id *cm_client_ids[NUM_QPS];
static struct ibv_comp_channel *io_completion_channels[NUM_QPS];
static struct ibv_cq *client_cqs[NUM_QPS];
static struct ibv_qp *client_qps[NUM_QPS];
static struct ibv_qp_init_attr qp_init_attrs[NUM_QPS];
std::vector<struct ibv_mr *> client_buffer_mrs;
static struct rdma_buffer_attr_vec client_metadata_attrs;
// extern struct ggml_tensor * prompt_sparse_tensor[400];
//TODO
sockaddr_in get_server_sockaddr(char *ip, char * port)
{
struct sockaddr_in server_sockaddr;
int ret, option;
bzero(&server_sockaddr, sizeof server_sockaddr);
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
ret = get_addr(ip, (struct sockaddr*) &server_sockaddr);
if (!port) {
/* no port provided, use the default port */
server_sockaddr.sin_port = htons(DEFAULT_RDMA_PORT);
}
else
{ printf("port is %s\n",port);
server_sockaddr.sin_port = htons(strtol(port, NULL, 0));
}
if(ret) {
rdma_error("Invalid IP \n");
exit(1);
}
return server_sockaddr;
}
void printf_dim(ggml_tensor * t ,char * str ="") {
printf("%s:%s %s: %d %d %d %d\n", __func__, t->name, str,t->ne[0], t->ne[1], t->ne[2], t->ne[3]);
}
static int client_prepare_connection_api(struct sockaddr_in *s_addr)
{
struct rdma_cm_event *cm_event = NULL;
int ret = -1;
/* Open a channel used to report asynchronous communication event */
cm_event_channel = rdma_create_event_channel(); //代码创建了一个RDMA事件通道
if (!cm_event_channel) {
rdma_error("Creating cm event channel failed, errno: %d ,.%s \n", -errno, strerror(errno));
exit(1);
}
debug("RDMA CM event channel is created at : %p \n", cm_event_channel);
/* rdma_cm_id is the connection identifier (like socket) which is used
* to define an RDMA connection.
*/
for(int i=0;i<NUM_QPS;++i)
{
ret = rdma_create_id(cm_event_channel, &cm_client_ids[i], //函数创建一个RDMA连接标识符
NULL,
RDMA_PS_TCP);
if (ret) {
rdma_error("Creating cm id failed with errno: %d \n", -errno);
exit(1);
}
/* Resolve destination and optional source addresses from IP addresses to
* an RDMA address. If successful, the specified rdma_cm_id will be bound
* to a local device. */
ret = rdma_resolve_addr(cm_client_ids[i], NULL, (struct sockaddr*) s_addr, 2000); //函数将目标地址解析为RDMA地址,并将cm_client_id与本地设备绑定。
if (ret) {
rdma_error("Failed to resolve address, errno: %d \n", -errno);
exit(1);
}
debug("waiting for cm event: RDMA_CM_EVENT_ADDR_RESOLVED\n");//process_rdma_cm_event函数等待并处理RDMA_CM_EVENT_ADDR_RESOLVED事件,该事件表示RDMA地址已解析完成
ret = process_rdma_cm_event(cm_event_channel,
RDMA_CM_EVENT_ADDR_RESOLVED,
&cm_event);
if (ret) {
rdma_error("Failed to receive a valid event, ret = %d \n", ret);
exit(1);
}
/* we ack the event */
ret = rdma_ack_cm_event(cm_event); //确认接收到的事件
if (ret) {
rdma_error("Failed to acknowledge the CM event, errno: %d\n", -errno);
exit(1);
}
debug("RDMA address is resolved \n");
/* Resolves an RDMA route to the destination address in order to
* establish a connection */
ret = rdma_resolve_route(cm_client_ids[i], 2000); //函数解析到目标地址的RDMA路由,以建立连接
if (ret) {
rdma_error("Failed to resolve route, erno: %d \n", -errno);
exit(1);
}
debug("waiting for cm event: RDMA_CM_EVENT_ROUTE_RESOLVED\n");
ret = process_rdma_cm_event(cm_event_channel,
RDMA_CM_EVENT_ROUTE_RESOLVED,
&cm_event);
if (ret) {
rdma_error("Failed to receive a valid event, ret = %d \n", ret);
exit(1);
}
/* we ack the event */
ret = rdma_ack_cm_event(cm_event);//函数确认接收到的事件
if (ret) {
rdma_error("Failed to acknowledge the CM event, errno: %d \n", -errno);
exit(1);
}
printf("Trying to connect to server at : %s port: %d \n",
inet_ntoa(s_addr->sin_addr),
ntohs(s_addr->sin_port));
/* Protection Domain (PD) is similar to a "process abstraction"
* in the operating system. All resources are tied to a particular PD.
* And accessing recourses across PD will result in a protection fault.
*/
if(!i) pd = ibv_alloc_pd(cm_client_ids[0]->verbs);//函数分配一个保护域(Protection Domain),类似于操作系统中的"进程抽象",所有资源都与特定的保护域相关联
if (!pd) {
rdma_error("Failed to alloc pd, errno: %d \n", -errno);
exit(1);
}
debug("pd allocated at %p \n", pd);
/* Now we need a completion channel, were the I/O completion
* notifications are sent. Remember, this is different from connection
* management (CM) event notifications.
* A completion channel is also tied to an RDMA device, hence we will
* use cm_client_id->verbs.
*/
io_completion_channels[i] = ibv_create_comp_channel(cm_client_ids[i]->verbs); //函数创建一个完成通道(Completion Channel),用于发送I/O完成通知
if (!io_completion_channels[i]) {
rdma_error("Failed to create IO completion event channel, errno: %d\n",
-errno);
exit(1);
}
debug("completion event channel created at : %p \n", io_completion_channels[i]);
/* Now we create a completion queue (CQ) where actual I/O
* completion metadata is placed. The metadata is packed into a structure
* called struct ibv_wc (wc = work completion). ibv_wc has detailed
* information about the work completion. An I/O request in RDMA world
* is called "work" ;)
*/
client_cqs[i] = ibv_create_cq(cm_client_ids[i]->verbs /* which device*/, //ibv_create_cq函数创建一个完成队列(Completion Queue),用于存放实际的I/O完成元数据
CQ_CAPACITY /* maximum capacity*/,
NULL /* user context, not used here */,
io_completion_channels[i] /* which IO completion channel */,
0 /* signaling vector, not used here*/);
if (!client_cqs[i]) {
rdma_error("Failed to create CQ, errno: %d \n", -errno);
exit(1);
}
debug("CQ created at %p with %d elements \n", client_cqs[i], client_cqs[i]->cqe);
ret = ibv_req_notify_cq(client_cqs[i], 0); //ibv_req_notify_cq函数请求通知,以便在完成队列中有新的完成操作时得到通知
if (ret) {
rdma_error("Failed to request notifications, errno: %d\n", -errno);
exit(1);
}
/* Now the last step, set up the queue pair (send, recv) queues and their capacity.
* The capacity here is define statically but this can be probed from the
* device. We just use a small number as defined in rdma_common.h */
bzero(&qp_init_attrs[i], sizeof qp_init_attrs[i]);
qp_init_attrs[i].cap.max_recv_sge = MAX_SGE; /* Maximum SGE per receive posting */
qp_init_attrs[i].cap.max_recv_wr = MAX_WR; /* Maximum receive posting capacity */
qp_init_attrs[i].cap.max_send_sge = MAX_SGE; /* Maximum SGE per send posting */
qp_init_attrs[i].cap.max_send_wr = MAX_WR; /* Maximum send posting capacity */
qp_init_attrs[i].qp_type = IBV_QPT_RC; /* QP type, RC = Reliable connection */
/* We use same completion queue, but one can use different queues */
qp_init_attrs[i].recv_cq = client_cqs[i]; /* Where should I notify for receive completion operations */
qp_init_attrs[i].send_cq = client_cqs[i]; /* Where should I notify for send completion operations */
/*Lets create a QP */
ret = rdma_create_qp(cm_client_ids[i] /* which connection id */,
pd /* which protection domain*/,
&qp_init_attrs[i] /* Initial attributes */);
if (ret) {
rdma_error("Failed to create QP, errno: %d \n", -errno);
exit(1);
}
client_qps[i] = cm_client_ids[i]->qp;
debug("QP created at %p \n", client_qps[i]);
}
return 0;
}
static int client_recv_buffer(rdma_buffer_attr_vec & server_metadata_attrs ,int qp_index=0 )
{
int ret = -1;
server_metadata_mr = rdma_buffer_register(pd, //rdma_buffer_register函数来注册一个内存区域,该区域用于存储服务器的元数据。rdma_buffer_register函数接受一些参数,包括一个指向内存区域的指针、内存区域的大小以及访问权限。
&server_metadata_attrs,
sizeof(server_metadata_attrs),
(IBV_ACCESS_LOCAL_WRITE));
if(!server_metadata_mr){
rdma_error("Failed to setup the server metadata mr , -ENOMEM\n");
return -ENOMEM;
}
server_recv_sge.addr = (uint64_t) server_metadata_mr->addr;
server_recv_sge.length = (uint32_t) server_metadata_mr->length;
server_recv_sge.lkey = (uint32_t) server_metadata_mr->lkey;
/* now we link it to the request */
bzero(&server_recv_wr, sizeof(server_recv_wr)); //bzero函数将server_recv_wr结构体清零,并将server_recv_sge结构体的地址赋值给server_recv_wr的sg_list成员,将1赋值给server_recv_wr的num_sge成员。这些操作将接收缓冲区的属性与请求相关联。
server_recv_wr.sg_list = &server_recv_sge;
server_recv_wr.num_sge = 1;
ret = ibv_post_recv(client_qps[qp_index] /* which QP */, //代码调用ibv_post_recv函数来提交接收工作请求。该函数接受一些参数,包括一个指向客户端QP(Queue Pair)的指针、一个指向接收工作请求的指针以及一个指向错误工作请求的指针。如果提交成功,函数将返回0,否则返回一个非零值
&server_recv_wr /* receive work request*/,
&bad_server_recv_wr /* error WRs */);
if (ret) {
rdma_error("Failed to pre-post the receive buffer, errno: %d \n", ret);
return ret;
}
debug("Receive buffer pre-posting is successful \n");
return 0;
}
static int client_connect_to_server()
{
struct rdma_conn_param conn_param;
struct rdma_cm_event *cm_event = NULL;
int ret = -1;
bzero(&conn_param, sizeof(conn_param)); //rdma_conn_param 结构体变量 conn_param,并使用 bzero() 函数将其初始化为零。这个结构体用于设置连接参数,包括 initiator_depth、responder_resources 和 retry_count。
conn_param.initiator_depth = 15; //表示连接的发起者(客户端)可以同时发送的最大并发请求数。在这里,我们将其设置为 3,表示客户端可以同时发送最多 3 个请求
conn_param.responder_resources = 15; // responder_resources 表示连接的响应者(服务器)可以同时处理的最大并发请求数。同样地,我们将其设置为 3。
conn_param.retry_count = 60; // if fail, then how many times to retry
for(int i=0;i<NUM_QPS;++i)
{
debug("cm_client_ids[i] %p \n", cm_client_ids[i]);
ret = rdma_connect(cm_client_ids[i], &conn_param); //使用 rdma_connect() 函数来发起与服务器的连接。该函数接受一个 rdma_cm_id 结构体指针 cm_client_id 和一个 rdma_conn_param 结构体指针 conn_param 作为参数。
if (ret) {
rdma_error("Failed to connect to remote host , errno: %d\n", -errno);
return -errno;
}
debug("waiting for cm event: RDMA_CM_EVENT_ESTABLISHED\n");
ret = process_rdma_cm_event(cm_event_channel, //process_rdma_cm_event 函数等待并处理 RDMA_CM_EVENT_ESTABLISHED 事件,该事件表示客户端与服务器的连接已建立。
RDMA_CM_EVENT_ESTABLISHED,
&cm_event);
if (ret) {
printf("Failed to get cm event, ret = %d \n", ret);
return ret;
}
ret = rdma_ack_cm_event(cm_event);
if (ret) {
rdma_error("Failed to acknowledge cm event, errno: %d\n",
-errno);
return -errno;
}
printf("The client is connected successfully \n");
}
return 0;
}
std::vector<ibv_mr *> register_mrs(std::vector<ggml_tensor *> &tensor_src)
{
std::vector<ibv_mr *> client_src_mrs(tensor_src.size());
struct ibv_wc wc[2];
int ret = -1;
for(int i=0;i<tensor_src.size();++i){
if(tensor_src[i]->data==NULL)
{
printf("tensor_src[%d]->data==NULL\n",i);
}
else
{
printf("tensor_src[%d]->data!=NULL\n",i);
}
client_src_mrs[i] = rdma_buffer_register(pd, //rdma_buffer_register函数来注册一个名为client_src_mr的内存区域。这个内存区域包含了客户端要发送给服务器的数据。注册内存区域时,指定了访问权限,包括本地写入、远程读取和远程写入
tensor_src[i]->data,
ggml_nbytes(tensor_src[i]),
(ibv_access_flags)(IBV_ACCESS_LOCAL_WRITE|
IBV_ACCESS_REMOTE_READ|
IBV_ACCESS_REMOTE_WRITE));
if(!client_src_mrs[i]){
rdma_error("Failed to register the first buffer, ret = %d \n", ret);
exit(1);
}
}
return client_src_mrs;
}
void wait_for_server_ready(rdma_buffer_attr_vec & server_metadata_attrs ,int qp_index=0)
{
printf("Waiting for server to be ready \n");
struct ibv_wc wc;
int ret = -1;
ret = process_work_completion_events(io_completion_channels[qp_index], //process_work_completion_events函数来等待并处理两个工作完成事件。一个是发送工作请求的完成事件,另一个是接收服务器发送的缓冲区信息的完成事件。如果成功接收到两个工作完成事件,代码会打印服务器发送的缓冲区位置和凭证信息。
&wc, 1);
if(ret != 1) {
rdma_error("We failed to get 2 work completions , ret = %d \n",
ret);
exit(1);
}
debug("Server sent us its buffer location and credentials, showing \n");
show_rdma_buffer_attrs(&server_metadata_attrs);
}
//通过存储tensor_dst的信息的client_dst_mrs和服务端server_metadata_attrs的信息,从服务器读取数据
static int client_operation(std::vector<ibv_mr *> client_dst_mrs,rdma_buffer_attr_vec & server_metadata_attrs,ibv_wr_opcode opcode,int start,int end,int qp_index=0)
{
int size =client_dst_mrs.size();
struct ibv_wc wc[size];
int ret = -1;
/* Step 1: is to copy the local buffer into the remote buffer. We will
* reuse the previous variables. */
/* now we fill up SGE */
//将本地缓冲区的地址、长度和本地键(lkey)赋值给client_send_sge结构体,表示发送的数据。
printf("size=%d\n",size);
for(int i=0;i<size;++i)
{ printf("i=%d\n",i);
client_send_sge.addr = (uint64_t) client_dst_mrs[i]->addr;
client_send_sge.length = (uint32_t) client_dst_mrs[i]->length;
client_send_sge.lkey = client_dst_mrs[i]->lkey;
/* now we link to the send work request */ //初始化client_send_wr结构体,并设置相关参数,如SGE列表、SGE数量、操作码(IBV_WR_RDMA_READ)和发送标志(IBV_SEND_SIGNALED)。
bzero(&client_send_wr, sizeof(client_send_wr));
client_send_wr.sg_list = &client_send_sge;
client_send_wr.num_sge = 1;
client_send_wr.opcode = opcode;
client_send_wr.send_flags = opcode ==IBV_WR_RDMA_WRITE_WITH_IMM?0: IBV_SEND_SIGNALED;
/* we have to tell server side info for RDMA */ // 设置远程RDMA操作的相关信息,包括远程键和远程地址。
client_send_wr.wr.rdma.rkey = server_metadata_attrs.stags[i].remote_stag;
client_send_wr.wr.rdma.remote_addr = server_metadata_attrs.address[i];
/* Now we post it */
int ret = ibv_post_send(client_qps[qp_index], //函数将发送请求发送到RDMA队列中。
&client_send_wr,
&bad_client_send_wr);
if (ret) {
rdma_error("Failed to read client dst buffer from the master, errno: %d \n",
-errno);
return -errno;
}
if(client_send_wr.send_flags&&(i+1)%MAX_WR==0)
{
ret = process_work_completion_events(io_completion_channels[qp_index],
wc, MAX_WR);
if(ret != MAX_WR) {
rdma_error("We failed to get 2 work completions , ret = %d \n",
ret);
return ret;
}
}
/* Now we prepare a READ using same variables but for destination */ //将目标缓冲区的地址、长度和本地键赋值给client_send_sge结构体,表示接收的数据
}
printf("waiting for work completions \n");
if(client_send_wr.send_flags){
ret = process_work_completion_events(io_completion_channels[qp_index],
wc, size%MAX_WR);
if(ret != size%MAX_WR) {
rdma_error("We failed to get %d work completions , ret = %d %s\n",
size%MAX_WR,ret, strerror(errno));
return ret;
}
}
debug("Client side %d is complete \n",opcode);
return 0;
}
// ibv_mr * register_mrs_and_send(std::vector<ggml_tensor*> tensor_dsts,int qp_index=0 ) //该函数用于向连接的客户端发送服务器端缓冲区的元数据。
// {
// struct ibv_wc wc; //工作完成(work completion)结构体
// int ret = -1;
// size_t size = tensor_dsts.size();
// std::vector<ibv_mr *> buffer_mrs;
// buffer_mrs.resize(size);
// for(int i=0;i<size;++i)
// {
// buffer_mrs[i] = rdma_buffer_register(pd /* which protection domain */,
// tensor_dsts[i]->data,
// ggml_nbytes(tensor_dsts[i]) /* what size to allocate */,
// (ibv_access_flags)(IBV_ACCESS_LOCAL_WRITE|
// IBV_ACCESS_REMOTE_READ|
// IBV_ACCESS_REMOTE_WRITE) /* access permissions */);
// if(!buffer_mrs[i]){
// rdma_error("Server failed to create a buffer \n");
// /* we assume that it is due to out of memory error */
// }
// client_metadata_attrs.address[i] = (uint64_t) buffer_mrs[i]->addr;
// client_metadata_attrs.length[i] = (uint32_t) buffer_mrs[i]->length;
// client_metadata_attrs.stags[i].local_stag = (uint32_t) buffer_mrs[i]->lkey;
// }
// client_metadata_attrs.size = size;
// /* This buffer is used to transmit information about the above
// * buffer to the client. So this contains the metadata about the client
// * buffer. Hence this is called metadata buffer. Since this is already
// * on allocated, we just register it.
// * We need to prepare a send I/O operation that will tell the
// * client the address of the client buffer.
// */
// //代码准备一个发送操作,用于告知客户端服务器端缓冲区的地址。代码将服务器端缓冲区的地址、长度和本地标签信息填充到client_metadata_attr 结构体中
// ibv_mr * client_metadata_mr = rdma_buffer_register(pd /* which protection domain*/, //调用 rdma_buffer_register() 函数将其注册到保护域中
// &client_metadata_attrs /* which memory to register */,
// sizeof(client_metadata_attrs) /* what is the size of memory */,
// IBV_ACCESS_LOCAL_WRITE /* what access permission */);
// if(!client_metadata_mr){
// rdma_error("Server failed to create to hold client metadata \n");
// /* we assume that this is due to out of memory error */
// }
// /* We need to transmit this buffer. So we create a send request.
// * A send request consists of multiple SGE elements. In our case, we only
// * have one
// */
// //代码创建一个发送请求,并将 client_metadata_attr 结构体的信息填充到 client_send_sge 结构体中。接着,代码将 client_send_sge 结构体与发送请求关联,并设置发送请求的操作码为 IBV_WR_SEND,表示这是一个发送请求。代码还设置发送请求的标志为 IBV_SEND_SIGNALED,表示希望接收到发送完成的通知。
// // client_recv_buffer(client_metadata_mr);
// client_send_sge.addr = (uint64_t) &client_metadata_attrs;
// client_send_sge.length = sizeof(client_metadata_attrs);
// client_send_sge.lkey = client_metadata_mr->lkey;
// /* now we link this sge to the send request */
// bzero(&client_send_wr, sizeof(client_send_wr));
// client_send_wr.sg_list = &client_send_sge;
// client_send_wr.num_sge = 1; // only 1 SGE element in the array
// client_send_wr.opcode = IBV_WR_SEND; // This is a send request
// client_send_wr.send_flags = IBV_SEND_SIGNALED; // We want to get notification
// /* This is a fast data path operation. Posting an I/O request */
// // sleep(50);
// ret = ibv_post_send(client_qps[qp_index] /* which QP */,
// &client_send_wr /* Send request that we prepared before */,
// &bad_client_send_wr /* In case of error, this will contain failed requests */);
// if (ret) {
// rdma_error("Posting of client metdata failed, errno: %d \n",
// -errno);
// }
// //代码调用 ibv_post_send() 函数将发送请求提交到客户端的队列对列(QP)中,并检查是否提交成功。
// /* We check for completion notification */
// ret = process_work_completion_events(io_completion_channels[qp_index], &wc, 1);
// debug("Local buffer metadata has been sent to the client \n");
// printf("wait writer \n");
// // ret = process_work_completion_events(io_completion_channels[0], &wc, 1);
// // sleep(5);
// debug("Local buffer metadata has been sent to the client \n");
// return client_metadata_mr;
// }
ibv_mr * register_mrs_and_send(ggml_tensor* tensor_dsts[],int qp_index=0,int size =0) //该函数用于向连接的客户端发送服务器端缓冲区的元数据。
{
printf("register_mrs_and_send\n");
struct ibv_wc wc; //工作完成(work completion)结构体
int ret = -1;
std::vector<ibv_mr *> buffer_mrs;
buffer_mrs.resize(size);
for(int i=0;i<size;++i)
{ if(tensor_dsts[i]==NULL||tensor_dsts[i]->data==NULL)
{
printf("tensor_dsts[%d]->data==NULL\n",i);
}
buffer_mrs[i] = rdma_buffer_register(pd /* which protection domain */,
tensor_dsts[i]->data,
ggml_nbytes(tensor_dsts[i]) /* what size to allocate */,
(ibv_access_flags)(IBV_ACCESS_LOCAL_WRITE|
IBV_ACCESS_REMOTE_READ|
IBV_ACCESS_REMOTE_WRITE) /* access permissions */);
if(!buffer_mrs[i]){
rdma_error("Server failed to create a buffer \n");
/* we assume that it is due to out of memory error */
}
client_metadata_attrs.address[i] = (uint64_t) buffer_mrs[i]->addr;
client_metadata_attrs.length[i] = (uint32_t) buffer_mrs[i]->length;
client_metadata_attrs.stags[i].local_stag = (uint32_t) buffer_mrs[i]->lkey;
}
client_metadata_attrs.size = size;
/* This buffer is used to transmit information about the above
* buffer to the client. So this contains the metadata about the client
* buffer. Hence this is called metadata buffer. Since this is already
* on allocated, we just register it.
* We need to prepare a send I/O operation that will tell the
* client the address of the client buffer.
*/
//代码准备一个发送操作,用于告知客户端服务器端缓冲区的地址。代码将服务器端缓冲区的地址、长度和本地标签信息填充到client_metadata_attr 结构体中
ibv_mr * client_metadata_mr = rdma_buffer_register(pd /* which protection domain*/, //调用 rdma_buffer_register() 函数将其注册到保护域中
&client_metadata_attrs /* which memory to register */,
sizeof(client_metadata_attrs) /* what is the size of memory */,
IBV_ACCESS_LOCAL_WRITE /* what access permission */);
if(!client_metadata_mr){
rdma_error("Server failed to create to hold client metadata \n");
/* we assume that this is due to out of memory error */
}
/* We need to transmit this buffer. So we create a send request.
* A send request consists of multiple SGE elements. In our case, we only
* have one
*/
//代码创建一个发送请求,并将 client_metadata_attr 结构体的信息填充到 client_send_sge 结构体中。接着,代码将 client_send_sge 结构体与发送请求关联,并设置发送请求的操作码为 IBV_WR_SEND,表示这是一个发送请求。代码还设置发送请求的标志为 IBV_SEND_SIGNALED,表示希望接收到发送完成的通知。
// client_recv_buffer(client_metadata_mr);
client_send_sge.addr = (uint64_t) &client_metadata_attrs;
client_send_sge.length = sizeof(client_metadata_attrs);
client_send_sge.lkey = client_metadata_mr->lkey;
/* now we link this sge to the send request */
bzero(&client_send_wr, sizeof(client_send_wr));
client_send_wr.sg_list = &client_send_sge;
client_send_wr.num_sge = 1; // only 1 SGE element in the array
client_send_wr.opcode = IBV_WR_SEND; // This is a send request
client_send_wr.send_flags = IBV_SEND_SIGNALED; // We want to get notification
/* This is a fast data path operation. Posting an I/O request */
// sleep(50);
ret = ibv_post_send(client_qps[qp_index] /* which QP */,
&client_send_wr /* Send request that we prepared before */,
&bad_client_send_wr /* In case of error, this will contain failed requests */);
if (ret) {
rdma_error("Posting of client metdata failed, errno: %d \n",
-errno);
}
//代码调用 ibv_post_send() 函数将发送请求提交到客户端的队列对列(QP)中,并检查是否提交成功。
/* We check for completion notification */
ret = process_work_completion_events(io_completion_channels[qp_index], &wc, 1);
debug("Local buffer metadata has been sent to the client \n");
printf("wait writer \n");
// ret = process_work_completion_events(io_completion_channels[0], &wc, 1);
// sleep(5);
debug("Local buffer metadata has been sent to the client \n");
return client_metadata_mr;
}
static int client_disconnect_and_clean_LLM_vec_api(std::vector<ibv_mr *> &client_dst_mrs,std::vector<ibv_mr *> &client_src_mrs)
{
size_t size =client_dst_mrs.size();
struct rdma_cm_event *cm_event = NULL;
int ret = -1;
/* active disconnect from the client side
{
struct rdma_cm_event *cm_event = NULL;
int ret = -1;
/* active disconnect from the client side */
ret = rdma_disconnect(cm_client_id);
if (ret) {
rdma_error("Failed to disconnect, errno: %d \n", -errno);
//continuing anyways
}
ret = process_rdma_cm_event(cm_event_channel,
RDMA_CM_EVENT_DISCONNECTED,
&cm_event);
if (ret) {
rdma_error("Failed to get RDMA_CM_EVENT_DISCONNECTED event, ret = %d\n",
ret);
//continuing anyways
}
ret = rdma_ack_cm_event(cm_event);
if (ret) {
rdma_error("Failed to acknowledge cm event, errno: %d\n",
-errno);
//continuing anyways
}
/* Destroy QP */
rdma_destroy_qp(cm_client_id);
/* Destroy client cm id */
ret = rdma_destroy_id(cm_client_id);
if (ret) {
rdma_error("Failed to destroy client id cleanly, %d \n", -errno);
// we continue anyways;
}
/* Destroy CQ */
ret = ibv_destroy_cq(client_cq);
if (ret) {
rdma_error("Failed to destroy completion queue cleanly, %d \n", -errno);
// we continue anyways;
}
/* Destroy completion channel */
ret = ibv_destroy_comp_channel(io_completion_channel);
if (ret) {
rdma_error("Failed to destroy completion channel cleanly, %d \n", -errno);
// we continue anyways;
}
/* Destroy memory buffers */
for(int i=0;i<size;++i)
{
rdma_buffer_deregister(client_src_mrs[i]);
rdma_buffer_deregister(client_dst_mrs[i]);
}
rdma_buffer_deregister(server_metadata_mr);
rdma_buffer_deregister(client_metadata_mr);
/* We free the buffers */
// free(tensor_src->data);
// free(tensor_dst->data);
/* Destroy protection domain */
ret = ibv_dealloc_pd(pd);
if (ret) {
rdma_error("Failed to destroy client protection domain cleanly, %d \n", -errno);
// we continue anyways;
}
rdma_destroy_event_channel(cm_event_channel);
printf("Client resource clean up is complete \n");
return 0;
}
//=============rdma=====================
static size_t utf8_len(char src) {
const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
uint8_t highbits = static_cast<uint8_t>(src) >> 4;
return lookup[highbits];
}
static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
std::string result;
for (size_t pos = 0; ; pos += search.length()) {
auto new_pos = s.find(search, pos);
if (new_pos == std::string::npos) {
result += s.substr(pos, s.size() - pos);
break;
}
result += s.substr(pos, new_pos - pos) + replace;
pos = new_pos;
}
s = std::move(result);
}
static bool is_float_close(float a, float b, float abs_tol) {
// Check for non-negative tolerance
if (abs_tol < 0.0) {
throw std::invalid_argument("Tolerance must be non-negative");
}
// Exact equality check
if (a == b) {
return true;
}
// Check for infinities
if (std::isinf(a) || std::isinf(b)) {
return false;
}
// Regular comparison using the provided absolute tolerance
return std::fabs(b - a) <= abs_tol;
}
#ifdef GGML_USE_CPU_HBM
#include <hbwmalloc.h>
#endif
static void zeros(std::ofstream & file, size_t n) {
char zero = 0;
for (size_t i = 0; i < n; ++i) {
file.write(&zero, 1);
}
}
LLAMA_ATTRIBUTE_FORMAT(1, 2)
static std::string format(const char * fmt, ...) {
va_list ap;
va_list ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
int size = vsnprintf(NULL, 0, fmt, ap);
GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
std::vector<char> buf(size + 1);
int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
GGML_ASSERT(size2 == size);
va_end(ap2);
va_end(ap);
return std::string(buf.data(), size);
}
static size_t llama_set_vram_budget(double budget_gb, int gpu_device) {
#if defined(GGML_USE_CUBLAS)
if (!ggml_cublas_loaded()) {
throw std::runtime_error("CUDA is not loaded");
}
if (budget_gb < 0) {
// if the user didn't specify a budget, use all available memory
// and leave 256 MB as a safety margin
vram_budget_bytes = ggml_cuda_get_free_memory(gpu_device) - 256 * 1024 * 1024;
} else {
// otherwise, use the specified budget
vram_budget_bytes = (size_t) (budget_gb * 1024 * 1024 * 1024);
}
return vram_budget_bytes;
#else
return 0;
#endif
}
static bool llama_reduce_vram_budget(size_t budget_bytes) {
#if not defined(GGML_USE_CUBLAS)
throw std::runtime_error("CUDA is not enabled");
#endif
if (vram_budget_bytes >= budget_bytes) {
vram_budget_bytes -= budget_bytes;
return true;
}
return false;
}
//
// gguf constants (sync with gguf.py)
//
enum llm_arch {
LLM_ARCH_LLAMA,
LLM_ARCH_FALCON,
LLM_ARCH_BAICHUAN,
LLM_ARCH_GPT2,
LLM_ARCH_GPTJ,
LLM_ARCH_GPTNEOX,
LLM_ARCH_MPT,
LLM_ARCH_STARCODER,
LLM_ARCH_PERSIMMON,
LLM_ARCH_REFACT,
LLM_ARCH_BLOOM,
LLM_ARCH_STABLELM,
LLM_ARCH_UNKNOWN,
};
static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
{ LLM_ARCH_LLAMA, "llama" },
{ LLM_ARCH_FALCON, "falcon" },
{ LLM_ARCH_GPT2, "gpt2" },
{ LLM_ARCH_GPTJ, "gptj" },
{ LLM_ARCH_GPTNEOX, "gptneox" },
{ LLM_ARCH_MPT, "mpt" },
{ LLM_ARCH_BAICHUAN, "baichuan" },
{ LLM_ARCH_STARCODER, "starcoder" },
{ LLM_ARCH_PERSIMMON, "persimmon" },
{ LLM_ARCH_REFACT, "refact" },
{ LLM_ARCH_BLOOM, "bloom" },
{ LLM_ARCH_STABLELM, "stablelm" },
{ LLM_ARCH_UNKNOWN, "unknown" },
};
enum llm_kv {
LLM_KV_GENERAL_ARCHITECTURE,
LLM_KV_GENERAL_QUANTIZATION_VERSION,
LLM_KV_GENERAL_ALIGNMENT,
LLM_KV_GENERAL_NAME,
LLM_KV_GENERAL_AUTHOR,
LLM_KV_GENERAL_URL,
LLM_KV_GENERAL_DESCRIPTION,
LLM_KV_GENERAL_LICENSE,
LLM_KV_GENERAL_SOURCE_URL,
LLM_KV_GENERAL_SOURCE_HF_REPO,
LLM_KV_CONTEXT_LENGTH,
LLM_KV_EMBEDDING_LENGTH,
LLM_KV_BLOCK_COUNT,
LLM_KV_FEED_FORWARD_LENGTH,
LLM_KV_USE_PARALLEL_RESIDUAL,
LLM_KV_TENSOR_DATA_LAYOUT,
LLM_KV_ATTENTION_HEAD_COUNT,
LLM_KV_ATTENTION_HEAD_COUNT_KV,
LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
LLM_KV_ATTENTION_CLAMP_KQV,
LLM_KV_ATTENTION_LAYERNORM_EPS,
LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
LLM_KV_ROPE_DIMENSION_COUNT,
LLM_KV_ROPE_FREQ_BASE,
LLM_KV_ROPE_SCALE_LINEAR,
LLM_KV_ROPE_SCALING_TYPE,
LLM_KV_ROPE_SCALING_FACTOR,
LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
LLM_KV_ROPE_SCALING_FINETUNED,
LLM_KV_TOKENIZER_MODEL,
LLM_KV_TOKENIZER_LIST,
LLM_KV_TOKENIZER_TOKEN_TYPE,
LLM_KV_TOKENIZER_SCORES,
LLM_KV_TOKENIZER_MERGES,
LLM_KV_TOKENIZER_BOS_ID,
LLM_KV_TOKENIZER_EOS_ID,
LLM_KV_TOKENIZER_UNK_ID,
LLM_KV_TOKENIZER_SEP_ID,
LLM_KV_TOKENIZER_PAD_ID,
LLM_KV_TOKENIZER_HF_JSON,
LLM_KV_TOKENIZER_RWKV,
LLM_KV_SPARSE_THRESHOLD,
LLM_KV_SPLIT_VRAM_CAPACITY,
};
static std::map<llm_kv, std::string> LLM_KV_NAMES = {
{ LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
{ LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
{ LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
{ LLM_KV_GENERAL_NAME, "general.name" },
{ LLM_KV_GENERAL_AUTHOR, "general.author" },
{ LLM_KV_GENERAL_URL, "general.url" },
{ LLM_KV_GENERAL_DESCRIPTION, "general.description" },
{ LLM_KV_GENERAL_LICENSE, "general.license" },
{ LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
{ LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
{ LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
{ LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
{ LLM_KV_BLOCK_COUNT, "%s.block_count" },
{ LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
{ LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
{ LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
{ LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
{ LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
{ LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
{ LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
{ LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
{ LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
{ LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
{ LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
{ LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
{ LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
{ LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
{ LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
{ LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
{ LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
{ LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
{ LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
{ LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
{ LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
{ LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
{ LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
{ LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
{ LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
{ LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
{ LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
{ LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
{ LLM_KV_SPARSE_THRESHOLD, "powerinfer.sparse_threshold" },
{ LLM_KV_SPLIT_VRAM_CAPACITY, "split.vram_capacity" },
};
struct LLM_KV {
LLM_KV(llm_arch arch) : arch(arch) {}
llm_arch arch;
std::string operator()(llm_kv kv) const {
return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
}
};
enum llm_tensor {
LLM_TENSOR_TOKEN_EMBD,
LLM_TENSOR_TOKEN_EMBD_NORM,
LLM_TENSOR_POS_EMBD,
LLM_TENSOR_OUTPUT,
LLM_TENSOR_OUTPUT_NORM,
LLM_TENSOR_ROPE_FREQS,
LLM_TENSOR_ATTN_Q,
LLM_TENSOR_ATTN_K,