interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-rpc / transport-apple.cpp

486 lines · 18964 bytes Raw Blame History
1#include "transport-apple.h"
2#include "transport.h"
3#include "log.h"
4
5#include <infiniband/verbs.h>
6
7#include <cerrno>
8#include <cstdlib>
9#include <cstring>
10#include <string>
11#include <dlfcn.h>
12#include <poll.h>
13#include <sys/socket.h>
14#include <unistd.h>
15
16// Apple RDMA-over-Thunderbolt (see Apple TN3205).
17//
18// Apple's RDMA is quite different from what's supported in Linux - deserving of its own transport implementation.
19// see https://developer.apple.com/documentation/technotes/tn3205-low-latency-communication-with-rdma-over-thunderbolt for details
20// at a high level the main differences are:
21// UC(unreliable connection) on Apple vs RC(reliable connection) QP transport types on Linux (though in practice UC on Apple is still lossless)
22// fixed 128KiB stride on Apple vs variable chunk size on Linux
23// relying on Apple's hardware credit based flow control vs RNR NAKs + retries on Linux
24//
25// on Apple a SEND and its corresponding RECV must cover the same number of 4 KiB Thunderbolt frames,
26// so every SEND posts a whole 128KiB stride over the wire, even when partially filled.
27// (In testing 128KiB was the best performing among 32, 64, 128, 256)
28
29//TODO: add mechanism similar to https://github.com/ggml-org/llama.cpp/pull/29440 to prevent idle CPU from spinning
30static constexpr uint32_t RDMA_SEG_MAGIC = 0x52534547u; // "RSEG"
31static constexpr int RDMA_NBUF = 16; // ring depth (frames per direction)
32static constexpr size_t RDMA_FRAME = 4096; // Thunderbolt frame (fixed on Apple)
33static constexpr size_t RDMA_STRIDE = 128 * 1024; // 32 Thunderbolt frames; NBUF x this = 2 MiB pinned per direction
34static constexpr uint32_t RDMA_PSN = 0; // any value works if both sides match: UC has no retransmit
35static constexpr size_t RDMA_GID_SIZE = 16;
36
37static_assert(RDMA_STRIDE % RDMA_FRAME == 0, "RDMA_STRIDE must be a whole number of frames");
38// TN3205 counts queue depth in Thunderbolt frames, not work requests.
39static constexpr uint32_t RDMA_QP_WR = (uint32_t)RDMA_NBUF * (RDMA_STRIDE / RDMA_FRAME);
40static constexpr uint64_t RDMA_RECV_WR = 1ull << 20; // wr_id bit tagging recv completions
41static constexpr uint64_t RDMA_WR_IDX_MASK = 0xffff; // buffer index in the low bits of wr_id
42static constexpr uint8_t RDMA_SYNC_READY = 0x2A; // readiness-handshake byte (peer activated)
43
44struct rdma_seg_hdr {
45 uint32_t magic; // RDMA_SEG_MAGIC; a mismatch means the stream desynced
46 uint32_t len; // payload bytes in this frame; the rest of the stride is padding
47};
48static constexpr size_t RDMA_PAYLOAD = RDMA_STRIDE - sizeof(rdma_seg_hdr);
49
50struct apple_rdma_caps {
51 uint32_t qpn;
52 uint16_t lid;
53 uint16_t reserved;
54 uint8_t gid[RDMA_GID_SIZE];
55};
56
57static_assert(sizeof(apple_rdma_caps) == RPC_CONN_CAPS_SIZE, "apple_rdma_caps must match conn_caps size");
58
59struct apple_rdma::impl {
60 int fd = -1; // bootstrap TCP socket, kept as the liveness anchor
61
62 struct ibv_context * ctx = nullptr;
63 struct ibv_pd * pd = nullptr;
64 struct ibv_cq * cq = nullptr; // one CQ for both directions; RDMA_RECV_WR tags recv completions
65 struct ibv_qp * qp = nullptr;
66
67 uint8_t * send_mem = nullptr;
68 struct ibv_mr * send_mr = nullptr;
69 uint8_t * recv_mem = nullptr;
70 struct ibv_mr * recv_mr = nullptr;
71
72 int send_busy[RDMA_NBUF] = {}; // 1 while this buffer has a send in flight
73 // completed recv frames, oldest first: ring index, bytes already handed to
74 // the reader, and total payload length
75 struct { int buf; uint32_t off; uint32_t len; } inq[RDMA_NBUF] = {};
76 int inq_head = 0;
77 int inq_count = 0;
78 int pend_buf = -1;
79 uint32_t pend_len = 0;
80 bool broken = false;
81
82 uint32_t qpn = 0;
83 uint8_t port = 0;
84 int gid_idx = 0;
85 enum ibv_mtu path_mtu = IBV_MTU_1024;
86
87 int progress();
88 bool acquire_pending();
89 bool post_pending();
90
91 bool post_recv(int i) {
92 struct ibv_sge sge = {};
93 sge.addr = (uintptr_t)(recv_mem + (size_t)i * RDMA_STRIDE);
94 sge.length = (uint32_t)RDMA_STRIDE;
95 sge.lkey = recv_mr->lkey;
96 struct ibv_recv_wr wr = {}, * bad = nullptr;
97 wr.wr_id = RDMA_RECV_WR | (uint64_t)i;
98 wr.sg_list = &sge;
99 wr.num_sge = 1;
100 return ibv_post_recv(qp, &wr, &bad) == 0;
101 }
102
103 bool post_send(int i, size_t len) {
104 struct ibv_sge sge = {};
105 sge.addr = (uintptr_t)(send_mem + (size_t)i * RDMA_STRIDE);
106 sge.length = (uint32_t)len;
107 sge.lkey = send_mr->lkey;
108 struct ibv_send_wr wr = {}, * bad = nullptr;
109 wr.wr_id = (uint64_t)i;
110 wr.sg_list = &sge;
111 wr.num_sge = 1;
112 wr.opcode = IBV_WR_SEND;
113 wr.send_flags = IBV_SEND_SIGNALED;
114 return ibv_post_send(qp, &wr, &bad) == 0;
115 }
116
117 ~impl() {
118 broken = true;
119 // destroy the QP first: it can still write to the rings until it is gone.
120 // no IBV_QPS_ERR before it - Apple's provider then fails every region unmap.
121 if (qp) ibv_destroy_qp(qp);
122 if (send_mr) ibv_dereg_mr(send_mr);
123 if (recv_mr) ibv_dereg_mr(recv_mr);
124 free(send_mem);
125 free(recv_mem);
126 if (cq) ibv_destroy_cq(cq);
127 if (pd) ibv_dealloc_pd(pd);
128 if (ctx) ibv_close_device(ctx);
129 }
130};
131
132apple_rdma::apple_rdma(std::unique_ptr<impl> p) : pimpl(std::move(p)) {}
133
134apple_rdma::~apple_rdma() = default;
135
136bool apple_rdma::broken() const {
137 return pimpl->broken;
138}
139
140// The readiness handshake below still runs over the bootstrap socket, one byte
141// each way, before the transport is declared live.
142static bool tcp_send_byte(int fd, uint8_t b) {
143 ssize_t n;
144 do { n = ::send(fd, &b, sizeof(b), 0); } while (n < 0 && errno == EINTR);
145 return n == sizeof(b);
146}
147
148static bool tcp_recv_byte(int fd, uint8_t * b) {
149 ssize_t n;
150 do { n = ::recv(fd, b, sizeof(*b), 0); } while (n < 0 && errno == EINTR);
151 return n == (ssize_t)sizeof(*b);
152}
153
154// Index of the GID on this port equal to the target, or -1. Thunderbolt GIDs are
155// RoCEv2 IPv4-mapped (::ffff:a.b.c.d), so this matches the local TCP address.
156static int rdma_match_gid(struct ibv_context * ctx, uint8_t port, int gid_tbl_len,
157 const uint8_t * target, union ibv_gid * out) {
158 for (int i = 0; i < gid_tbl_len; i++) {
159 union ibv_gid g;
160 if (ibv_query_gid(ctx, port, i, &g) != 0) continue;
161 if (memcmp(g.raw, target, RDMA_GID_SIZE) != 0) continue;
162 if (out) *out = g;
163 return i;
164 }
165 return -1;
166}
167
168// First ACTIVE port on the device. Only a cabled, up Thunderbolt link reports
169// ACTIVE, and it is not always port 1, so the port cannot be hardcoded the way
170// the Linux path does. Returns 0 if none.
171static uint8_t rdma_first_active_port(struct ibv_context * ctx, struct ibv_port_attr * out) {
172 struct ibv_device_attr da;
173 if (ibv_query_device(ctx, &da) != 0) return 0;
174 for (uint8_t p = 1; p <= da.phys_port_cnt; p++) {
175 struct ibv_port_attr pa;
176 if (ibv_query_port(ctx, p, &pa) != 0) continue;
177 if (pa.state == IBV_PORT_ACTIVE) { if (out) *out = pa; return p; }
178 }
179 return 0;
180}
181
182// librdma.dylib is weak-linked, so its symbols are null when it is absent. Nothing may
183// call one before this has returned true.
184static bool rdma_library_present() {
185 static const bool present = [] {
186 void * handle = dlopen("/usr/lib/librdma.dylib", RTLD_LAZY);
187 if (handle == nullptr) {
188 return false;
189 }
190 dlclose(handle);
191 return true;
192 }();
193 return present;
194}
195
196// Called before the endpoints are exchanged: pick the local device facing this
197// peer, create a UC QP and register the frame rings. RDMA is point-to-point, so
198// the device is the one whose GID equals the bootstrap connection's local
199// address, i.e. the one cabled to the peer.
200std::unique_ptr<apple_rdma> apple_rdma::probe(int fd, const uint8_t * target_gid, uint8_t * caps) {
201 if (!rdma_library_present()) {
202 LOG_DBG2("[RDMA(Apple)] librdma.dylib not present, continuing with TCP\n");
203 return nullptr;
204 }
205 int ndev = 0;
206 ibv_device ** devs = ibv_get_device_list(&ndev);
207 if (!devs) return nullptr;
208
209 ibv_context * ctx = nullptr;
210 uint8_t port = 0;
211 struct ibv_port_attr pa = {};
212 union ibv_gid gid = {};
213 int gid_idx = -1;
214 std::string matched;
215 for (int d = 0; d < ndev; d++) {
216 ibv_context * c = ibv_open_device(devs[d]);
217 if (!c) continue;
218 struct ibv_port_attr p = {};
219 uint8_t pt = rdma_first_active_port(c, &p);
220 int gi = pt ? rdma_match_gid(c, pt, p.gid_tbl_len, target_gid, &gid) : -1;
221 if (gi < 0) { ibv_close_device(c); continue; }
222 ctx = c; port = pt; pa = p; gid_idx = gi;
223 const char * name = ibv_get_device_name(devs[d]);
224 matched = name ? name : "";
225 break;
226 }
227 ibv_free_device_list(devs);
228 if (!ctx) {
229 LOG_DBG2("[RDMA(Apple)] no RDMA device matched the connection address, continuing with TCP\n");
230 return nullptr;
231 }
232
233 std::unique_ptr<impl> c(new impl());
234 c->fd = fd;
235 c->ctx = ctx;
236 c->port = port;
237 c->gid_idx = gid_idx;
238 c->path_mtu = pa.active_mtu;
239
240 c->pd = ibv_alloc_pd(ctx);
241 if (!c->pd) return nullptr;
242
243 c->cq = ibv_create_cq(ctx, 2 * RDMA_QP_WR + 1, nullptr, nullptr, 0);
244 if (!c->cq) return nullptr;
245
246 ibv_qp_init_attr qia = {};
247 qia.send_cq = c->cq;
248 qia.recv_cq = c->cq;
249 qia.qp_type = IBV_QPT_UC;
250 qia.cap.max_send_wr = RDMA_QP_WR;
251 qia.cap.max_recv_wr = RDMA_QP_WR;
252 qia.cap.max_send_sge = 1;
253 qia.cap.max_recv_sge = 1;
254 c->qp = ibv_create_qp(c->pd, &qia);
255 if (!c->qp) return nullptr;
256
257 {
258 ibv_qp_attr a = {};
259 a.qp_state = IBV_QPS_INIT;
260 a.pkey_index = 0;
261 a.port_num = port;
262 a.qp_access_flags = IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_REMOTE_WRITE;
263 if (ibv_modify_qp(c->qp, &a,
264 IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS) != 0) {
265 return nullptr;
266 }
267 }
268
269 long page = sysconf(_SC_PAGESIZE);
270 if (page <= 0) page = 4096;
271 const size_t ring_bytes = (size_t)RDMA_NBUF * RDMA_STRIDE;
272 if (posix_memalign((void **)&c->send_mem, (size_t)page, ring_bytes) != 0) c->send_mem = nullptr;
273 if (posix_memalign((void **)&c->recv_mem, (size_t)page, ring_bytes) != 0) c->recv_mem = nullptr;
274 if (!c->send_mem || !c->recv_mem) return nullptr;
275
276 // Apple's provider rejects LOCAL_WRITE-only MRs even for two-sided SEND/RECV.
277 const int mr_flags = IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_REMOTE_WRITE;
278 c->send_mr = ibv_reg_mr(c->pd, c->send_mem, ring_bytes, mr_flags);
279 c->recv_mr = ibv_reg_mr(c->pd, c->recv_mem, ring_bytes, mr_flags);
280 if (!c->send_mr || !c->recv_mr) return nullptr;
281
282 // Recvs are posted in activate() after the RTS transition, not here: Apple's
283 // provider rejects ibv_post_recv on a QP that has not reached RTS.
284
285 c->qpn = c->qp->qp_num;
286
287 apple_rdma_caps rc = {};
288 rc.qpn = c->qpn;
289 rc.lid = pa.lid;
290 memcpy(rc.gid, gid.raw, RDMA_GID_SIZE);
291 memcpy(caps, &rc, sizeof(rc));
292
293 LOG_INFO("RDMA(Apple/UC) probed: dev=%s port=%u gid=%d qpn=%u lid=%u mtu=%d ring=%d x %zu KiB\n",
294 matched.c_str(), port, gid_idx, c->qpn, (unsigned)pa.lid, 128 << c->path_mtu,
295 RDMA_NBUF, RDMA_STRIDE / 1024);
296 return std::unique_ptr<apple_rdma>(new apple_rdma(std::move(c)));
297}
298
299// Called once the peer's endpoint has arrived: INIT -> RTR -> RTS (UC: GID/GRH
300// addressing, no timeout/retry/rnr/rd_atomic), then the readiness handshake.
301bool apple_rdma::activate(const uint8_t * caps) {
302 impl * c = pimpl.get();
303
304 apple_rdma_caps rc = {};
305 memcpy(&rc, caps, sizeof(rc));
306
307 bool ok = true;
308 {
309 ibv_qp_attr a = {};
310 a.qp_state = IBV_QPS_RTR;
311 a.path_mtu = c->path_mtu;
312 a.rq_psn = RDMA_PSN;
313 a.dest_qp_num = rc.qpn;
314 a.ah_attr.is_global = 1;
315 a.ah_attr.port_num = c->port;
316 a.ah_attr.sl = 0;
317 a.ah_attr.src_path_bits = 0;
318 a.ah_attr.dlid = rc.lid;
319 a.ah_attr.grh.hop_limit = 1;
320 a.ah_attr.grh.sgid_index = (uint8_t)c->gid_idx;
321 memcpy(&a.ah_attr.grh.dgid, rc.gid, RDMA_GID_SIZE);
322 if (ibv_modify_qp(c->qp, &a,
323 IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN | IBV_QP_RQ_PSN) != 0) {
324 LOG_ERROR("RDMA(Apple/UC) RTR failed: %s\n", strerror(errno));
325 ok = false;
326 }
327 }
328 if (ok) {
329 ibv_qp_attr a = {};
330 a.qp_state = IBV_QPS_RTS;
331 a.sq_psn = RDMA_PSN;
332 if (ibv_modify_qp(c->qp, &a, IBV_QP_STATE | IBV_QP_SQ_PSN) != 0) {
333 LOG_ERROR("RDMA(Apple/UC) RTS failed: %s\n", strerror(errno));
334 ok = false;
335 }
336 }
337
338 // Recvs are posted only now: the controller starts processing them at RTR.
339 for (int i = 0; ok && i < RDMA_NBUF; i++) {
340 if (!c->post_recv(i)) {
341 LOG_ERROR("RDMA(Apple/UC) post_recv %d/%d failed\n", i, RDMA_NBUF);
342 ok = false;
343 }
344 }
345
346 // A queue pair processes receives only after RTR and the transitions above can
347 // fail on one side alone, so neither peer sends a frame until both report their
348 // recvs posted.
349 uint8_t peer_ready = 0;
350 if (!tcp_send_byte(c->fd, ok ? RDMA_SYNC_READY : 0) || !tcp_recv_byte(c->fd, &peer_ready)) {
351 return false;
352 }
353 if (!ok || peer_ready != RDMA_SYNC_READY) {
354 return false;
355 }
356
357 LOG_INFO("RDMA(Apple/UC) activated: qpn=%u->%u mtu=%d rx_depth=%d\n",
358 c->qpn, rc.qpn, 128 << c->path_mtu, RDMA_NBUF);
359 return true;
360}
361
362// Drain the CQ: release completed send buffers, queue completed recv frames for
363// the reader. Returns the number of completions reaped, or -1 on error.
364int apple_rdma::impl::progress() {
365 struct ibv_wc wc[RDMA_NBUF * 2];
366 int n = ibv_poll_cq(cq, RDMA_NBUF * 2, wc);
367 if (n < 0) { LOG_ERROR("RDMA(Apple/UC) poll_cq failed\n"); broken = true; return -1; }
368 for (int j = 0; j < n; j++) {
369 uint64_t id = wc[j].wr_id;
370 bool is_recv = (id & RDMA_RECV_WR) != 0;
371 if (wc[j].status != IBV_WC_SUCCESS) {
372 LOG_ERROR("RDMA(Apple/UC) %s wc error: status=%d\n", is_recv ? "recv" : "send", wc[j].status);
373 broken = true;
374 return -1;
375 }
376 if (is_recv) {
377 int b = (int)(id & RDMA_WR_IDX_MASK);
378 const rdma_seg_hdr * h = (const rdma_seg_hdr *)(recv_mem + (size_t)b * RDMA_STRIDE);
379 if (h->magic != RDMA_SEG_MAGIC) { LOG_ERROR("RDMA(Apple/UC) bad frame magic\n"); broken = true; return -1; }
380 if (h->len > RDMA_PAYLOAD) { LOG_ERROR("RDMA(Apple/UC) frame len %u exceeds payload\n", h->len); broken = true; return -1; }
381 int slot = (inq_head + inq_count) % RDMA_NBUF;
382 inq[slot].buf = b;
383 inq[slot].off = 0;
384 inq[slot].len = h->len;
385 inq_count++;
386 } else {
387 send_busy[(int)(id & RDMA_WR_IDX_MASK)] = 0;
388 }
389 }
390 return n;
391}
392
393// Reserve a free send buffer to coalesce into, waiting on progress if none free.
394bool apple_rdma::impl::acquire_pending() {
395 if (pend_buf >= 0) return true;
396 for (;;) {
397 if (broken) return false;
398 for (int k = 0; k < RDMA_NBUF; k++) if (!send_busy[k]) { pend_buf = k; pend_len = 0; return true; }
399 if (progress() < 0) return false;
400 }
401}
402
403// Post the pending frame. The whole STRIDE goes out even when only partly filled:
404// TN3205 requires a SEND and its matching RECV to cover the same number of
405// Thunderbolt frames, so a short send would fail the peer's receive.
406bool apple_rdma::impl::post_pending() {
407 if (pend_buf < 0) return true;
408 int i = pend_buf;
409 rdma_seg_hdr * h = (rdma_seg_hdr *)(send_mem + (size_t)i * RDMA_STRIDE);
410 h->magic = RDMA_SEG_MAGIC;
411 h->len = pend_len;
412 if (!post_send(i, RDMA_STRIDE)) { broken = true; return false; }
413 send_busy[i] = 1;
414 pend_buf = -1;
415 pend_len = 0;
416 return true;
417}
418
419// Coalescing write: append into the pending frame, posting a full frame when it
420// fills. The trailing partial is posted by flush() at each message boundary.
421bool apple_rdma::send(const void * data, size_t size) {
422 impl * c = pimpl.get();
423 const uint8_t * p = (const uint8_t *)data;
424 while (size > 0) {
425 if (c->broken) return false;
426 if (!c->acquire_pending()) return false;
427 uint8_t * sb = c->send_mem + (size_t)c->pend_buf * RDMA_STRIDE;
428 size_t space = RDMA_PAYLOAD - c->pend_len;
429 size_t chunk = size < space ? size : space;
430 memcpy(sb + sizeof(rdma_seg_hdr) + c->pend_len, p, chunk);
431 c->pend_len += (uint32_t)chunk;
432 p += chunk;
433 size -= chunk;
434 if (c->pend_len == RDMA_PAYLOAD) { if (!c->post_pending()) return false; }
435 }
436 return true;
437}
438
439bool apple_rdma::recv(void * data, size_t size) {
440 impl * c = pimpl.get();
441 uint8_t * p = (uint8_t *)data;
442 if (!c->post_pending()) return false; // turnaround: flush the coalesced request
443 unsigned idle = 0;
444 while (size > 0) {
445 if (c->inq_count == 0) {
446 if (c->broken) return false;
447 int n = c->progress();
448 if (n < 0) return false;
449 if (n == 0) {
450 // UC gives no disconnect notification, so the bootstrap TCP fd is
451 // the liveness anchor: nothing crosses it once RDMA is up, so any
452 // readability means the peer's FIN (macOS has no POLLRDHUP).
453 // Same idle interval as the Linux path.
454 if ((++idle & 0xFFFFF) == 0) {
455 struct pollfd pfd = { c->fd, POLLIN, 0 };
456 if (poll(&pfd, 1, 0) > 0 &&
457 (pfd.revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL))) {
458 return false;
459 }
460 }
461 } else {
462 idle = 0;
463 }
464 continue;
465 }
466 idle = 0;
467 int slot = c->inq_head;
468 int b = c->inq[slot].buf;
469 uint32_t avail = c->inq[slot].len - c->inq[slot].off;
470 uint32_t take = (size < (size_t)avail) ? (uint32_t)size : avail;
471 memcpy(p, c->recv_mem + (size_t)b * RDMA_STRIDE + sizeof(rdma_seg_hdr) + c->inq[slot].off, take);
472 p += take;
473 size -= take;
474 c->inq[slot].off += take;
475 if (c->inq[slot].off == c->inq[slot].len) {
476 if (!c->post_recv(b)) { c->broken = true; return false; }
477 c->inq_head = (c->inq_head + 1) % RDMA_NBUF;
478 c->inq_count--;
479 }
480 }
481 return true;
482}
483
484bool apple_rdma::flush() {
485 return pimpl->post_pending();
486}