forked from uccl-project/uccl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.cc
More file actions
2502 lines (2149 loc) · 82.7 KB
/
Copy pathengine.cc
File metadata and controls
2502 lines (2149 loc) · 82.7 KB
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
#include "engine.h"
#include "compression.h"
#include "endpoint_wrapper.h"
#include "util/debug.h"
#include "util/gpu_rt.h"
#include "util/pause.h"
#include "util/util.h"
#include <arpa/inet.h>
#include <cc/cc_state.h>
#include <netinet/in.h>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <future>
#include <iostream>
#include <optional>
#include <sstream>
#include <thread>
#include <Python.h>
#include <sys/socket.h>
#include <unistd.h>
thread_local bool inside_python = false;
std::size_t VectorUint8Hash::operator()(std::vector<uint8_t> const& vec) const {
std::size_t hash = vec.size();
for (uint8_t byte : vec) {
hash = hash * 31 + static_cast<std::size_t>(byte);
}
return hash;
}
ShmMsg::ShmMsg() : type(ShmMsgType::COMPLETION), completion(0) {
std::memset(src_bdf, 0, sizeof(src_bdf));
}
// TaskBatch (declaration order: after ShmMsg, before Endpoint)
TaskBatch::TaskBatch() : num_iovs(0) {}
TaskBatch::TaskBatch(TaskBatch&& other) noexcept
: num_iovs(other.num_iovs),
data_ptr(std::move(other.data_ptr)),
size_ptr(std::move(other.size_ptr)),
mr_id_ptr(std::move(other.mr_id_ptr)),
slot_item_ptr(std::move(other.slot_item_ptr)) {}
TaskBatch& TaskBatch::operator=(TaskBatch&& other) noexcept {
if (this != &other) {
num_iovs = other.num_iovs;
data_ptr = std::move(other.data_ptr);
size_ptr = std::move(other.size_ptr);
mr_id_ptr = std::move(other.mr_id_ptr);
slot_item_ptr = std::move(other.slot_item_ptr);
}
return *this;
}
void** TaskBatch::data_v() const {
if (!data_ptr) return nullptr;
return data_ptr->data();
}
size_t* TaskBatch::size_v() const {
if (!size_ptr) return nullptr;
return size_ptr->data();
}
uint64_t* TaskBatch::mr_id_v() const {
if (!mr_id_ptr) return nullptr;
return mr_id_ptr->data();
}
FifoItem* TaskBatch::slot_item_v() const {
if (!slot_item_ptr) return nullptr;
return slot_item_ptr->data();
}
// UnifiedTask (declaration order: after TaskBatch, before Endpoint)
UnifiedTask::UnifiedTask()
: type(TaskType::WRITE_NET),
data(nullptr),
size(0),
conn_id(0),
mr_id(0),
status_ptr(nullptr),
specific() {}
UnifiedTask::~UnifiedTask() {
if (is_batch_task()) {
specific.batch.task_batch.~TaskBatch();
}
}
FifoItem& UnifiedTask::slot_item() { return specific.net.slot_item; }
FifoItem const& UnifiedTask::slot_item() const {
return specific.net.slot_item;
}
IpcTransferInfo& UnifiedTask::ipc_info() { return specific.ipc.ipc_info; }
IpcTransferInfo const& UnifiedTask::ipc_info() const {
return specific.ipc.ipc_info;
}
TaskBatch& UnifiedTask::task_batch() { return specific.batch.task_batch; }
TaskBatch const& UnifiedTask::task_batch() const {
return specific.batch.task_batch;
}
bool UnifiedTask::is_batch_task() const {
return type == TaskType::WRITEV || type == TaskType::READV;
}
UnifiedTask::SpecificData::SpecificData() : base{} {}
UnifiedTask::SpecificData::~SpecificData() {}
static inline void check_python_signals() {
PyGILState_STATE gstate = PyGILState_Ensure();
if (PyErr_CheckSignals() != 0) {
UCCL_LOG(FATAL) << "Python signal caught, exiting...";
}
PyGILState_Release(gstate);
}
static inline bool is_retryable_post_failure(int rc) {
if (is_cxi_transport()) return rc == UCCL_POST_TRANSIENT;
return rc == -1;
}
static inline bool raw_one_sided_batch_eligible(
std::vector<size_t> const& size_v, size_t num_iovs) {
for (size_t i = 0; i < num_iovs; ++i) {
if (ChunkSplitStrategy::get_message_chunk_count(size_v[i]) != 1)
return false;
}
return true;
}
static inline size_t max_iov_bytes(std::vector<size_t> const& size_v,
size_t num_iovs) {
size_t max_bytes = 0;
for (size_t i = 0; i < num_iovs; ++i) {
max_bytes = std::max(max_bytes, size_v[i]);
}
return max_bytes;
}
size_t Endpoint::max_one_sided_inflight_ops() {
size_t limit = kMaxInflightOps;
if (is_cxi_transport()) limit = 32;
char const* env = std::getenv("UCCL_P2P_MAX_INFLIGHT_OPS");
if (env && env[0] != '\0') {
char* end = nullptr;
unsigned long requested = std::strtoul(env, &end, 10);
if (end != env && requested > 0) {
limit = std::min<size_t>(requested, kMaxInflightOps);
}
}
return std::max<size_t>(1, limit);
}
// ShmChannel helper function
static inline std::string shm_ring_name(std::string const& from_bdf,
std::string const& to_bdf) {
return "/uccl_gpu_jring_" + uccl::sanitize_bdf(from_bdf) + "_" +
uccl::sanitize_bdf(to_bdf);
}
static inline void shm_ring_send(jring_t* ring, ShmMsg const& msg) {
// jring bulk copy requires 16B aligned buffer
alignas(16) ShmMsg tmp = msg;
while (jring_mp_enqueue_bulk(ring, (void*)&tmp, 1, nullptr) != 1) {
machnet_pause();
}
}
static inline void shm_ring_recv(jring_t* ring, ShmMsg& msg) {
alignas(16) ShmMsg tmp;
while (jring_sc_dequeue_bulk(ring, (void*)&tmp, 1, nullptr) != 1) {
machnet_pause();
}
msg = tmp;
}
uccl::UCCLLogLevel Endpoint::parse_log_level_from_env() {
char const* env = std::getenv("UCCL_P2P_LOG_LEVEL");
if (!env) {
return uccl::WARN;
}
if (!strcasecmp(env, "INFO")) return uccl::INFO;
if (!strcasecmp(env, "WARN") || !strcasecmp(env, "WARNING"))
return uccl::WARN;
if (!strcasecmp(env, "ERROR")) return uccl::ERROR;
if (!strcasecmp(env, "FATAL")) return uccl::FATAL;
char* end = nullptr;
long val = std::strtol(env, &end, 10);
if (end != env && val >= 0 && val <= 3) {
return static_cast<uccl::UCCLLogLevel>(val);
}
return uccl::WARN;
}
// -----------------------------------------------------------------------------
// The main P2P Endpoint class implementation
// -----------------------------------------------------------------------------
Endpoint::Endpoint(uint32_t const gpu_idx) : passive_accept_(false) {
// gpu_idx is always a local CUDA device ordinal.
int ngpus = 0;
GPU_RT_CHECK(gpuGetDeviceCount(&ngpus));
UCCL_CHECK(static_cast<int>(gpu_idx) < ngpus)
<< "GPU index " << gpu_idx << " out of range (visible devices: " << ngpus
<< ")";
local_gpu_idx_ = gpu_idx;
// Get PCI Bus ID as cross-process identity
char bdf_buf[64];
GPU_RT_CHECK(gpuDeviceGetPCIBusId(bdf_buf, sizeof(bdf_buf), gpu_idx));
gpu_bus_id_ = uccl::normalize_pci_bus_id(bdf_buf);
std::cout << "Creating Engine with GPU index: " << gpu_idx
<< " (bus_id: " << gpu_bus_id_ << ")" << std::endl;
int n_streams = std::max(1, (int)kNumGpuRtStreams);
ipc_streams_.resize(ngpus);
for (int i = 0; i < ngpus; ++i) {
GPU_RT_CHECK(gpuSetDevice(i));
ipc_streams_[i].resize(n_streams);
for (int j = 0; j < n_streams; ++j) {
GPU_RT_CHECK(
gpuStreamCreateWithFlags(&ipc_streams_[i][j], gpuStreamNonBlocking));
}
}
GPU_RT_CHECK(gpuSetDevice(local_gpu_idx_));
uccl::ucclLogger.setLogLevel(Endpoint::parse_log_level_from_env());
if (is_nccl_transport()) {
ep_ = std::make_shared<NCCLEndpoint>(local_gpu_idx_, 0);
numa_node_ = get_numa_node_from_iface();
} else if (is_cxi_transport()) {
ep_ = std::make_shared<CxiEndpoint>(local_gpu_idx_, 0);
numa_node_ = get_numa_node_from_iface();
} else {
ep_ = std::shared_ptr<RDMAEndpoint>(new RDMAEndpoint(local_gpu_idx_, 0));
}
std::cout << "Engine initialized for GPU " << local_gpu_idx_ << std::endl;
engine_initialized_ = true;
send_unified_task_ring_ =
uccl::create_ring(sizeof(UnifiedTask*), kTaskRingSize);
recv_unified_task_ring_ =
uccl::create_ring(sizeof(UnifiedTask*), kTaskRingSize);
if (!is_nccl_transport() && !is_cxi_transport()) {
numa_node_ = RdmaDeviceManager::instance().get_numa_node(
RdmaDeviceManager::instance().get_best_dev_idx(local_gpu_idx_)[0]);
}
send_proxy_thread_ = std::thread(&Endpoint::send_proxy_thread_func, this);
recv_proxy_thread_ = std::thread(&Endpoint::recv_proxy_thread_func, this);
ipc_inflight_ring_ = uccl::create_ring(sizeof(IpcInflightOp*), kTaskRingSize);
ipc_poller_thread_ = std::thread(&Endpoint::ipc_poller_thread_func, this);
// Initialize ShmChannel for local connections (use BDF for ring names)
size_t elem_sz = sizeof(ShmMsg);
size_t elem_cnt = ShmRingDefaultElemCnt;
auto all_bdfs = uccl::enumerate_all_gpu_bdfs();
for (auto const& sender_bdf : all_bdfs) {
auto name = shm_ring_name(sender_bdf, gpu_bus_id_);
ShmRingHandle handle;
handle.shm_name = name;
bool is_creator = false;
handle.ring =
uccl::create_shared_ring(name.c_str(), elem_sz, elem_cnt, handle.shm_fd,
handle.shm_size, &is_creator);
inbox_rings_[sender_bdf] = handle;
inbox_creators_[sender_bdf] = is_creator;
}
std::cout << "Endpoint initialized successfully" << std::endl;
}
Endpoint::Endpoint() : local_gpu_idx_(INVALID_GPU), passive_accept_(false) {
std::cout << "Creating Engine" << std::endl;
int n_streams = std::max(1, (int)kNumGpuRtStreams);
int ngpus = 0;
GPU_RT_CHECK(gpuGetDeviceCount(&ngpus));
// Save the current device before the loop so we can restore it afterwards.
// The loop calls gpuSetDevice(i) for each GPU, leaving the active device as
// GPU ngpus-1, which would corrupt gpu_bus_id_ and the advertised BDF.
int cur_dev = 0;
GPU_RT_CHECK(gpuGetDevice(&cur_dev));
ipc_streams_.resize(ngpus);
for (int i = 0; i < ngpus; ++i) {
GPU_RT_CHECK(gpuSetDevice(i));
ipc_streams_[i].resize(n_streams);
for (int j = 0; j < n_streams; ++j) {
GPU_RT_CHECK(
gpuStreamCreateWithFlags(&ipc_streams_[i][j], gpuStreamNonBlocking));
}
}
GPU_RT_CHECK(gpuSetDevice(cur_dev));
// Get the current GPU's BDF for metadata (needed before lazy engine init).
char bdf_buf[64];
GPU_RT_CHECK(gpuDeviceGetPCIBusId(bdf_buf, sizeof(bdf_buf), cur_dev));
gpu_bus_id_ = uccl::normalize_pci_bus_id(bdf_buf);
if (is_nccl_transport()) {
ep_ = std::make_shared<NCCLEndpoint>(local_gpu_idx_, 0);
} else if (is_cxi_transport()) {
ep_ = std::make_shared<CxiEndpoint>(INVALID_GPU, 0);
} else {
ep_ = std::shared_ptr<RDMAEndpoint>(new RDMAEndpoint(INVALID_GPU, 0));
}
std::cout << "Endpoint initialized successfully" << std::endl;
}
Endpoint::~Endpoint() {
std::cout << "Destroying Engine..." << std::endl;
stop_.store(true, std::memory_order_release);
if (passive_accept_) {
passive_accept_stop_.store(true, std::memory_order_release);
if (passive_accept_thread_.joinable()) {
passive_accept_thread_.join();
}
if (passive_accept_local_thread_.joinable()) {
passive_accept_local_thread_.join();
}
}
if (send_proxy_thread_.joinable()) {
send_proxy_thread_.join();
}
if (recv_proxy_thread_.joinable()) {
recv_proxy_thread_.join();
}
if (ipc_poller_thread_.joinable()) {
ipc_poller_thread_.join();
}
if (send_unified_task_ring_ != nullptr) {
free(send_unified_task_ring_);
}
if (recv_unified_task_ring_ != nullptr) {
free(recv_unified_task_ring_);
}
if (ipc_inflight_ring_ != nullptr) {
free(ipc_inflight_ring_);
}
{
std::shared_lock<std::shared_mutex> lock(conn_mu_);
for (auto& [conn_id, conn] : conn_id_to_conn_) {
auto& shm_channel_ = conn->remote_inbox_;
if (conn->shm_attached_) {
uccl::detach_shared_ring(shm_channel_.ring, shm_channel_.shm_fd,
shm_channel_.shm_size);
}
delete conn;
}
}
for (auto& [bdf, handle] : inbox_rings_) {
auto it = inbox_creators_.find(bdf);
if (it != inbox_creators_.end() && it->second)
uccl::destroy_shared_ring(handle.shm_name.c_str(), handle.ring,
handle.shm_fd, handle.shm_size);
else
uccl::detach_shared_ring(handle.ring, handle.shm_fd, handle.shm_size);
}
{
std::shared_lock<std::shared_mutex> lock(mr_mu_);
for (auto& [mr_id, mr] : mr_id_to_mr_) {
delete mr->mhandle_;
delete mr;
}
}
std::cout << "Engine destroyed" << std::endl;
}
void Endpoint::stop_accept() { uccl_stop_accept(ep_); }
bool Endpoint::connect(std::string ip_addr, int remote_gpu_idx, int remote_port,
uint64_t& conn_id) {
std::cout << "Attempting to connect to " << ip_addr << ":" << remote_gpu_idx
<< " via port " << remote_port << std::endl;
// Create a new connection ID
conn_id = next_conn_id_.fetch_add(1);
assert(local_gpu_idx_ != INVALID_GPU);
std::future<ConnID> uccl_conn_id_future = std::async(
std::launch::async, [this, remote_gpu_idx, &ip_addr, remote_port]() {
return uccl_connect(ep_, remote_gpu_idx, ip_addr, remote_port);
});
// Check for Python signals (eg, ctrl+c) while waiting for connection
while (uccl_conn_id_future.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready) {
auto _ = inside_python ? (check_python_signals(), nullptr) : nullptr;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
ConnID uccl_conn_id = uccl_conn_id_future.get();
// Store the connection ID.
{
std::unique_lock<std::shared_mutex> lock(conn_mu_);
conn_id_to_conn_[conn_id] = new Conn{
conn_id, uccl_conn_id, ip_addr, static_cast<uint16_t>(remote_port), ""};
}
return true;
}
std::vector<uint8_t> Endpoint::get_metadata() {
std::string ip_str = uccl::get_oob_ip();
uint16_t port = get_p2p_listen_port(ep_);
bool is_ipv6 = ip_str.find(':') != std::string::npos;
size_t ip_len = is_ipv6 ? 16 : 4;
// 2 bytes port + 1 byte BDF length + N bytes BDF string
uint8_t bdf_len = static_cast<uint8_t>(gpu_bus_id_.size());
size_t total_len = ip_len + 2 + 1 + bdf_len;
std::vector<uint8_t> metadata(total_len);
// Copy IP
if (is_ipv6) {
struct in6_addr ip6_bin;
if (inet_pton(AF_INET6, ip_str.c_str(), &ip6_bin) != 1)
throw std::runtime_error("Invalid IPv6 address: " + ip_str);
std::memcpy(metadata.data(), &ip6_bin, 16);
} else {
struct in_addr ip4_bin;
if (inet_pton(AF_INET, ip_str.c_str(), &ip4_bin) != 1)
throw std::runtime_error("Invalid IPv4 address: " + ip_str);
std::memcpy(metadata.data(), &ip4_bin, 4);
}
// Copy port in network byte order
uint16_t net_port = htons(port);
std::memcpy(metadata.data() + ip_len, &net_port, 2);
// Copy BDF string (1 byte length + string data)
metadata[ip_len + 2] = bdf_len;
std::memcpy(metadata.data() + ip_len + 3, gpu_bus_id_.data(), bdf_len);
return metadata;
}
std::tuple<std::string, uint16_t, std::string> Endpoint::parse_metadata(
std::vector<uint8_t> const& metadata) {
// Minimum: 4 (IPv4) + 2 (port) + 1 (bdf_len) = 7
if (metadata.size() < 7) {
throw std::runtime_error("Metadata too short: " +
std::to_string(metadata.size()));
}
std::string ip_str;
size_t ip_len;
// Determine IP version from metadata length and BDF field
// Try IPv4 first: 4 bytes IP + 2 bytes port + 1 byte bdf_len + N bytes bdf
uint8_t bdf_len_v4 = metadata[6];
if (metadata.size() == static_cast<size_t>(4 + 2 + 1 + bdf_len_v4)) {
// IPv4
ip_len = 4;
char buf[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, metadata.data(), buf, sizeof(buf)) == nullptr) {
throw std::runtime_error("Failed to parse IPv4 address from metadata");
}
ip_str = buf;
} else {
// IPv6: 16 bytes IP + 2 bytes port + 1 byte bdf_len + N bytes bdf
ip_len = 16;
if (metadata.size() < 19) {
throw std::runtime_error("Metadata too short for IPv6: " +
std::to_string(metadata.size()));
}
uint8_t bdf_len_v6 = metadata[18];
if (metadata.size() != static_cast<size_t>(19 + bdf_len_v6)) {
throw std::runtime_error("Metadata size mismatch for IPv6: got " +
std::to_string(metadata.size()) + ", expected " +
std::to_string(19 + bdf_len_v6));
}
char buf[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, metadata.data(), buf, sizeof(buf)) == nullptr) {
throw std::runtime_error("Failed to parse IPv6 address from metadata");
}
ip_str = buf;
}
uint16_t net_port;
std::memcpy(&net_port, metadata.data() + ip_len, 2);
uint16_t port = ntohs(net_port);
uint8_t bdf_len = metadata[ip_len + 2];
std::string gpu_bdf;
if (bdf_len > 0) {
gpu_bdf = std::string(
reinterpret_cast<char const*>(metadata.data() + ip_len + 3), bdf_len);
}
return std::make_tuple(ip_str, port, gpu_bdf);
}
bool Endpoint::accept(std::string& ip_addr, int& remote_gpu_idx,
uint64_t& conn_id) {
std::cout << "Waiting to accept incoming connection..." << std::endl;
// For demo purposes, simulate accepted connection
conn_id = next_conn_id_.fetch_add(1);
// Wait until engine is intialized to get the correct local_gpu_idx_
while (!engine_initialized_) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::future<ConnID> uccl_conn_id_future =
std::async(std::launch::async, [this, &ip_addr, &remote_gpu_idx]() {
return uccl_accept(ep_, ip_addr, &remote_gpu_idx);
});
// Check for Python signals (eg, ctrl+c) while waiting for connection
while (uccl_conn_id_future.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready) {
if (passive_accept_ &&
passive_accept_stop_.load(std::memory_order_acquire)) {
std::cout << "Stop background accept..." << std::endl;
uccl_stop_accept(ep_);
}
auto _ = inside_python ? (check_python_signals(), nullptr) : nullptr;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
ConnID uccl_conn_id = uccl_conn_id_future.get();
// Return if Conn ID is invalid
if (uccl_conn_id.sock_fd < 0 || uccl_conn_id.peer_id == UINT64_MAX) {
return false;
}
// Store the connection ID.
{
std::unique_lock<std::shared_mutex> lock(conn_mu_);
conn_id_to_conn_[conn_id] = new Conn{conn_id, uccl_conn_id, ip_addr, 0, ""};
}
return true;
}
bool Endpoint::reg(void const* data, size_t size, uint64_t& mr_id,
FloatType float_type) {
mr_id = next_mr_id_.fetch_add(1);
if (!engine_initialized_) {
int idx = uccl::get_dev_idx((void*)data);
if (idx != -1) {
local_gpu_idx_ = idx;
} else {
local_gpu_idx_ = 0;
}
// Get PCI Bus ID for cross-process identity
char bdf_buf[64];
GPU_RT_CHECK(
gpuDeviceGetPCIBusId(bdf_buf, sizeof(bdf_buf), local_gpu_idx_));
gpu_bus_id_ = uccl::normalize_pci_bus_id(bdf_buf);
initialize_engine();
engine_initialized_ = true;
}
P2PMhandle* mhandle = new P2PMhandle();
mhandle->compress_ctx = make_compress_ctx(float_type);
if (!uccl_regmr(ep_, const_cast<void*>(data), size, mhandle)) {
delete mhandle;
return false;
}
{
std::unique_lock<std::shared_mutex> lock(mr_mu_);
mr_id_to_mr_[mr_id] = new MR{mr_id, mhandle};
}
return true;
}
bool Endpoint::regv(std::vector<void const*> const& data_v,
std::vector<size_t> const& size_v,
std::vector<uint64_t>& mr_id_v) {
if (data_v.size() != size_v.size())
throw std::invalid_argument(
"[Endpoint::regv] data_v/size_v length mismatch");
size_t const n = data_v.size();
// Early return if empty
if (n == 0) {
mr_id_v.clear();
return true;
}
if (!engine_initialized_) {
int idx = uccl::get_dev_idx((void*)data_v[0]);
if (idx != -1) {
local_gpu_idx_ = idx;
} else {
local_gpu_idx_ = 0;
}
char bdf_buf[64];
GPU_RT_CHECK(
gpuDeviceGetPCIBusId(bdf_buf, sizeof(bdf_buf), local_gpu_idx_));
gpu_bus_id_ = uccl::normalize_pci_bus_id(bdf_buf);
initialize_engine();
engine_initialized_ = true;
}
mr_id_v.resize(n);
{
std::unique_lock<std::shared_mutex> lock(mr_mu_);
mr_id_to_mr_.reserve(mr_id_to_mr_.size() + n);
}
for (size_t i = 0; i < n; ++i) {
uint64_t id = next_mr_id_.fetch_add(1);
P2PMhandle* mhandle = new P2PMhandle();
if (!uccl_regmr(ep_, const_cast<void*>(data_v[i]), size_v[i], mhandle)) {
std::cerr << "[Endpoint::regv] registration failed at i=" << i << '\n';
return false;
}
{
std::unique_lock<std::shared_mutex> lock(mr_mu_);
mr_id_to_mr_[id] = new MR{id, mhandle};
}
mr_id_v[i] = id;
}
return true;
}
bool Endpoint::dereg(uint64_t mr_id) {
MR* mr = nullptr;
{
std::unique_lock<std::shared_mutex> lock(mr_mu_);
auto it = mr_id_to_mr_.find(mr_id);
if (it == mr_id_to_mr_.end()) {
std::cerr << "[dereg] Error: Invalid mr_id " << mr_id << std::endl;
return false;
}
mr = it->second;
mr_id_to_mr_.erase(mr_id);
}
mr->mhandle_->compress_ctx.reset();
uccl_deregmr(ep_, mr->mhandle_);
delete mr->mhandle_;
delete mr;
return true;
}
bool Endpoint::read(uint64_t conn_id, uint64_t mr_id, void* dst, size_t size,
FifoItem const& slot_item) {
UCCL_DCHECK(size <= 0xffffffff) << "size must be < 4 GB";
auto* conn = get_conn(conn_id);
if (unlikely(conn == nullptr)) {
std::cerr << "[read] Error: Invalid conn_id " << conn_id << std::endl;
return false;
}
P2PMhandle* mhandle = get_mhandle(mr_id);
if (unlikely(mhandle == nullptr)) {
std::cerr << "[read] Error: Invalid mr_id " << mr_id << std::endl;
return false;
}
UcclRequest ureq = {};
FifoItem curr_slot_item = slot_item;
curr_slot_item.size = size;
int rc;
do {
rc = uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, &ureq);
} while (is_retryable_post_failure(rc));
if (is_cxi_transport() && rc < 0) {
UCCL_LOG(ERROR) << "read failed to post: rc=" << rc;
return false;
}
bool done = false;
while (!done) {
auto _ = inside_python ? (check_python_signals(), nullptr) : nullptr;
uccl_drive_recv(ep_);
if (uccl_poll_ureq_once(ep_, &ureq)) {
done = true;
}
}
return true;
}
bool Endpoint::read_async(uint64_t conn_id, uint64_t mr_id, void* dst,
size_t size, FifoItem const& slot_item,
uint64_t* transfer_id) {
if (size <= kDirectAsyncNetThreshold) {
auto* conn = get_conn(conn_id);
if (unlikely(conn == nullptr)) {
std::cerr << "[read_async] Error: Invalid conn_id " << conn_id
<< std::endl;
return false;
}
P2PMhandle* mhandle = get_mhandle(mr_id);
if (unlikely(mhandle == nullptr)) {
std::cerr << "[read_async] Error: Invalid mr_id " << mr_id << std::endl;
return false;
}
UcclRequest ureq = {};
FifoItem curr_slot_item = slot_item;
curr_slot_item.size = size;
int rc;
do {
rc =
uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, &ureq);
} while (is_retryable_post_failure(rc));
if (is_cxi_transport() && rc < 0) {
UCCL_LOG(ERROR) << "read_async failed to post: rc=" << rc;
return false;
}
auto* status = new TransferStatus();
status->poll_net_ureq = true;
status->ureq = ureq;
*transfer_id = reinterpret_cast<uint64_t>(status);
return true;
}
auto task_ptr =
create_net_task(conn_id, mr_id, TaskType::READ_NET, dst, size, slot_item);
if (unlikely(task_ptr == nullptr)) {
return false;
}
auto* status = new TransferStatus();
status->task_ptr = task_ptr;
task_ptr->status_ptr = status;
*transfer_id = reinterpret_cast<uint64_t>(status);
UnifiedTask* task_raw = task_ptr.get();
while (jring_mp_enqueue_bulk(recv_unified_task_ring_, &task_raw, 1,
nullptr) != 1) {
}
recv_proxy_adaptive_sleeper_.maybe_wake_proxy_thread();
return true;
}
bool Endpoint::readv(uint64_t conn_id, std::vector<uint64_t> const& mr_id_v,
std::vector<void*> const& dst_v,
std::vector<size_t> const& size_v,
std::vector<FifoItem> const& slot_item_v,
size_t num_iovs) {
auto* conn = get_conn(conn_id);
if (unlikely(conn == nullptr)) {
std::cerr << "[readv] Error: Invalid conn_id " << conn_id << std::endl;
return false;
}
// Pre-resolve all mhandles once to avoid per-iov mutex + map lookup.
std::vector<P2PMhandle*> mhandle_v(num_iovs);
for (size_t i = 0; i < num_iovs; ++i) {
mhandle_v[i] = get_mhandle(mr_id_v[i]);
if (unlikely(mhandle_v[i] == nullptr)) {
std::cerr << "[readv] Error: Invalid mr_id " << mr_id_v[i] << std::endl;
return false;
}
}
// Enable doorbell-batched posting for the duration of this call.
struct BatchGuard {
BatchGuard() { g_uccl_batch_post = true; }
~BatchGuard() { g_uccl_batch_post = false; }
} batch_guard;
// Resolve the send group once so per-slot completion checks avoid the
// per-call shared_lock + map.find().
SendConnection* send_group =
uccl_resolve_send_group(ep_, conn->uccl_conn_id_.peer_id);
if (send_group != nullptr && raw_one_sided_batch_eligible(size_v, num_iovs) &&
send_group->can_use_raw_one_sided_batch(
SendType::Read, max_iov_bytes(size_v, num_iovs))) {
return run_raw_one_sided_pipeline(send_group, SendType::Read, mhandle_v,
dst_v, size_v, slot_item_v, num_iovs);
}
UcclRequest ureq[kMaxInflightOps] = {};
bool active[kMaxInflightOps] = {false};
size_t const max_inflight_ops = max_one_sided_inflight_ops();
size_t next_iov = 0;
size_t num_completed = 0;
size_t num_inflight = 0;
while (num_completed < num_iovs) {
while (next_iov < num_iovs && num_inflight < max_inflight_ops) {
size_t slot = 0;
while (slot < kMaxInflightOps && active[slot]) {
slot++;
}
UCCL_DCHECK(slot < kMaxInflightOps);
auto rc =
send_group != nullptr
? uccl_read_async_on_group(send_group, conn, mhandle_v[next_iov],
dst_v[next_iov], size_v[next_iov],
slot_item_v[next_iov], &ureq[slot])
: uccl_read_async(ep_, conn, mhandle_v[next_iov], dst_v[next_iov],
size_v[next_iov], slot_item_v[next_iov],
&ureq[slot]);
if (is_retryable_post_failure(rc)) {
if (is_cxi_transport() && num_inflight == 0) {
uccl_drive_send(ep_);
uccl_drive_recv(ep_);
std::this_thread::yield();
continue;
}
break;
}
if (is_cxi_transport() && rc < 0) {
UCCL_LOG(ERROR) << "readv failed to post iov " << next_iov
<< ": rc=" << rc;
return false;
}
active[slot] = true;
next_iov++;
num_inflight++;
}
auto _ = inside_python ? (check_python_signals(), nullptr) : nullptr;
// Flush batched WRs in one doorbell per channel, then drive send once.
// (readv issues RDMA reads via the send path, so drive send here.)
if (num_inflight > 0) {
uccl_flush_send(ep_);
uccl_drive_send(ep_);
uccl_drive_recv(ep_);
}
if (send_group != nullptr) {
for (size_t slot = 0; slot < kMaxInflightOps; slot++) {
if (!active[slot]) continue;
if (uccl_check_wr_fast(send_group, ureq[slot].engine_idx)) {
active[slot] = false;
num_completed++;
num_inflight--;
}
}
} else {
for (size_t slot = 0; slot < kMaxInflightOps; slot++) {
if (!active[slot]) continue;
if (uccl_check_ureq_once(ep_, &ureq[slot])) {
active[slot] = false;
num_completed++;
num_inflight--;
}
}
}
}
return true;
}
bool Endpoint::readv_async(uint64_t conn_id, std::vector<uint64_t> mr_id_v,
std::vector<void*> dst_v, std::vector<size_t> size_v,
std::vector<FifoItem> slot_item_v, size_t num_iovs,
uint64_t* transfer_id) {
// Use move semantics to reduce memory copies
auto task_ptr =
create_readv_task(conn_id, std::move(dst_v), std::move(size_v),
std::move(mr_id_v), std::move(slot_item_v));
if (unlikely(task_ptr == nullptr)) {
return false;
}
auto* status = new TransferStatus();
status->task_ptr = task_ptr;
task_ptr->status_ptr = status;
*transfer_id = reinterpret_cast<uint64_t>(status);
UnifiedTask* task_raw = task_ptr.get();
while (jring_mp_enqueue_bulk(recv_unified_task_ring_, &task_raw, 1,
nullptr) != 1) {
}
recv_proxy_adaptive_sleeper_.maybe_wake_proxy_thread();
return true;
}
bool Endpoint::run_raw_one_sided_pipeline(
SendConnection* send_group, SendType send_type,
std::vector<P2PMhandle*> const& mhandle_v,
std::vector<void*> const& local_addr_v, std::vector<size_t> const& size_v,
std::vector<FifoItem> const& slot_item_v, size_t num_iovs) {
struct PendingRawWait {
SendConnection::RawBatchWait wait;
bool active = false;
};
std::array<PendingRawWait, kMaxInflightOps> pending_waits{};
size_t const max_inflight_ops = max_one_sided_inflight_ops();
size_t next_iov = 0;
size_t num_completed = 0;
size_t num_inflight = 0;
auto post_raw_window = [&]() -> bool {
if (next_iov >= num_iovs || num_inflight >= max_inflight_ops) return true;
size_t const batch_iovs =
std::min<size_t>(max_inflight_ops - num_inflight, num_iovs - next_iov);
std::array<SendConnection::OneSidedBatchOp, kMaxInflightOps> ops{};
int64_t wr_ids[kMaxInflightOps] = {};
std::array<SendConnection::RawBatchWait, kMaxInflightOps> waits{};
size_t num_waits = 0;
for (size_t i = 0; i < batch_iovs; ++i) {
size_t const iov = next_iov + i;
ops[i].local_addr = local_addr_v[iov];
ops[i].size = size_v[iov];
ops[i].local_mr_array = &mhandle_v[iov]->mr_array;
ops[i].slot_item = &slot_item_v[iov];
}
if (!send_group->post_write_or_read_batch(send_type, ops.data(), batch_iovs,
wr_ids, waits.data(),
&num_waits)) {
return false;
}
if (unlikely(num_waits == 0)) return false;
for (size_t i = 0; i < num_waits; ++i) {
bool inserted = false;
for (auto& pending : pending_waits) {
if (pending.active) continue;
pending.wait = waits[i];
pending.active = true;
inserted = true;
break;
}
if (unlikely(!inserted)) return false;
}
next_iov += batch_iovs;
num_inflight += batch_iovs;
return true;
};
while (num_completed < num_iovs) {
while (next_iov < num_iovs && num_inflight < max_inflight_ops) {
if (!post_raw_window()) return false;
}
auto _ = inside_python ? (check_python_signals(), nullptr) : nullptr;
uccl_drive_send(ep_);
for (auto& pending : pending_waits) {
if (!pending.active) continue;
if (!uccl_check_wr_fast(send_group, pending.wait.wr_id)) continue;
pending.active = false;
num_completed += pending.wait.iov_count;
UCCL_DCHECK(num_inflight >= pending.wait.iov_count);
num_inflight -= pending.wait.iov_count;
pending.wait = {};
}
}
return true;
}
bool Endpoint::write(uint64_t conn_id, uint64_t mr_id, void* src, size_t size,