Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/189856
Note: Links to docs will display an error until the docs builds have been completed. ❌ 18 New Failures, 1 Unclassified FailureAs of commit 29f4b13 with merge base 3cc7a98 ( NEW FAILURES - The following jobs have failed:
UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
There was a problem hiding this comment.
Pull request overview
This PR introduces TCCL as an in-tree c10d::Backend to enable torch.distributed collectives on Apple Silicon MPS tensors via RDMA over Thunderbolt, wiring it through the Python API, dispatcher registrations, build configuration, and adding an env-launched multi-node correctness/integration test suite.
Changes:
- Add
ProcessGroupTCCL+ transport/algorithm layers (TCCLUtils.*,ProcessGroupTCCLDetail.*) and expose TCCL diagnostics to Python (is_tccl_available,list_tccl_devices,check_tccl_link_layer). - Integrate the backend into distributed backend registration/defaults and c10d dispatcher device registrations for MPS.
- Add build-time opt-in (
USE_TCCL/USE_C10D_TCCL) and a new multi-node TCCL test module.
Reviewed changes
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| torch/testing/_internal/common_distributed.py | Adds requires_tccl() skip helper for tests. |
| torch/distributed/distributed_c10d.py | Registers TCCL backend, exposes Python availability/diagnostics helpers, and updates backend/device mappings. |
| torch/csrc/distributed/c10d/TCCLUtils.hpp | New TCCL transport-layer types and helper APIs (RDMA wrapper, connection, buffers, Store bootstrap helpers). |
| torch/csrc/distributed/c10d/TCCLUtils.cpp | New implementation for RDMA dlopen/dlsym wrapper, device discovery, link-layer checks, and Store bootstrap helpers. |
| torch/csrc/distributed/c10d/ProcessGroupTCCLDetail.hpp | New collective engine API + reduction template definitions. |
| torch/csrc/distributed/c10d/ProcessGroupTCCLDetail.ipp | New collective algorithm implementations (mesh/ring primitives and collectives). |
| torch/csrc/distributed/c10d/ProcessGroupTCCL.hpp | New c10d::Backend subclass definition, Options, Work type, and async worker scaffolding. |
| torch/csrc/distributed/c10d/ProcessGroupTCCL.cpp | New backend implementation (MPS event synchronization, CPU views, collective overrides, worker loop). |
| torch/csrc/distributed/c10d/Ops.cpp | Registers c10d dispatcher kernels for the MPS device key. |
| torch/csrc/distributed/c10d/init.cpp | Adds pybind exposure for ProcessGroupTCCL and TCCL diagnostics helpers. |
| test/distributed/test_c10d_tccl.py | Adds env-launched, multi-node TCCL correctness/contract/integration tests. |
| setup.py | Registers the backend entry point for tccl. |
| CMakeLists.txt | Adds USE_TCCL / USE_C10D_TCCL build options (Apple-only, opt-in). |
| cmake/Dependencies.cmake | Adds librdma + verbs header probe for USE_TCCL. |
| caffe2/CMakeLists.txt | Adds include/link wiring for librdma when TCCL is enabled. |
| build_variables.bzl | Adds TCCL sources to distributed build source list. |
| at::Tensor mpsSharedCpuView(const at::Tensor& mpsTensor) { | ||
| auto* allocator = at::mps::getIMPSAllocator(); | ||
| const void* storage_ptr = mpsTensor.storage().data_ptr().get(); | ||
| auto [cpu_ptr, retain_count] = allocator->getSharedBufferPtr(storage_ptr); |
There was a problem hiding this comment.
Yes. Though we can just take .first of the tuple instead of voiding it, that's cleaner I think. Will include that change:
- auto [cpu_ptr, retain_count] = allocator->getSharedBufferPtr(storage_ptr);
+ const void* cpu_ptr = allocator->getSharedBufferPtr(storage_ptr).first; // [cpu_ptr, retain_count] | // Build the result Future (mirrors ProcessGroupGloo::createFutureAsOutput): | ||
| // carries a List[Tensor]; its device list is the outputs' non-CPU devices so | ||
| // device-aware consumers (DDP's reducer) chain correctly. | ||
|
|
||
| future_ = c10::make_intrusive<c10::ivalue::Future>( | ||
| c10::ListType::create(c10::TensorType::get())); | ||
| } |
There was a problem hiding this comment.
This is a stale comment from an earlier dev device-aware version we abandoned on purpose. The code intentionally builds the Future without a device list. To my understanding, device list exists to ensure event ordering across streams against pending async GPU work. But that doesn't apply to this backend because:
- MPS is single-queue, there is no other queue to synchronize with
- The collective runs on a CPU worker thread = no GPU work to track at all
- DDP's reducer still chains correctly: when the Future fires the data is already in place
It's also a measured performance decision as the device list added ~140 µs/op of pure overhead that doesn't synchronize anything. We of course tested the correctness of the no-device Future, so correctness is unaffected.
I'll update the comment.
| # TCCL (Thunderbolt RDMA) is the MPS backend when torch is built with | ||
| # USE_C10D_TCCL. Without it (_TCCL_AVAILABLE == False) this maps to Gloo, | ||
| # which will raise on MPS tensors. | ||
| "mps": TCCL if _TCCL_AVAILABLE else GLOO, | ||
| } |
There was a problem hiding this comment.
Yes, this is incorrect handling coming from an earlier dev version. Very easy fix. We remove the if and only map mps to TCCL backend.
default_device_backend_map: dict[str, str] = {
"cpu": GLOO,
"cuda": NCCL,
"xpu": XCCL,
- "mps": TCCL if _TCCL_AVAILABLE else GLOO,
+ "mps": TCCL,
}I'll commit the update.
|
|
f1a9eed to
5b1e800
Compare
ddd3348 to
9d1ac45
Compare
|
Amazing job!!! |
6e54ee5 to
66918c3
Compare
TCCL (Thunderbolt Collective Communication Library) is a low-latency communication backend running collectives on Apple Silicon over Thunderbolt 5. TCCL enables all exposed parallelism strategies, such as distributed data parallelism, tensor parallelism, pipeline parallelism, etc.
…d map - mpsSharedCpuView: take .first instead of an unused structured binding (fixes -Wunused-variable under -Werror). - TCCLWork Future: correct the stale comment; the Future intentionally has no device list (single-queue MPS + CPU-worker collective have nothing to order; a device list added ~140us/op of no-op overhead). - default_device_backend_map: map "mps" to TCCL unconditionally instead of falling back to Gloo (which can't serve MPS); a non-TCCL build now raises a clear "rebuild with USE_TCCL=1" error at backend creation. Test Plan: Reran the complete test suite with applied fixes.
…her/scatter Optimize the TCCL collective engine and complete its collective coverage. Optimizations (large-message bandwidth): - bidirectional (double) ring for ring all-reduce, all-gather, reduce-scatter - depth-2 pipelining + double-buffered staging in the ring, p2p, the 2-node mesh fast path, and the multi-peer mesh all-gather - native __bf16 reduce for bf16 all-reduce - on FEAT_BF16 hardware the __bf16 add lowers to a single correctly-rounded fp32 add, bitwise identical to the fp32-accumulate fallback, without the per-element convert loop - lower the fp32/fp16 all-reduce ring threshold 8MB -> 1MB - TCCL_PATH_MTU knob to select the RTR path MTU New collectives (the c10d frontend exposes these; TCCL previously stubbed them): - reduce: reuses the tuned ring/mesh all-reduce, a correct superset of reduce's rooted contract (result on every rank; only the root is guaranteed) - gather / scatter: multi-peer mesh engine, mesh-only since the root needs a queue pair to every rank Tests: extend test_c10d_tccl.py with ragged / chunk-boundary ring cases that exercise the bidir ring + depth-2 pipeline, and reduce/gather/scatter coverage (four dtypes, SUM/AVG/MAX/PRODUCT, zero and non-zero roots, ring-reject cases). Test Plan: In-tree suite + out-of-tree exhaustive matrix at world size 2, 3, 4 over the Thunderbolt mesh, both ring and mesh forced: N=2: 321 in-tree OK; 6912/6912 out-of-tree PASSED N=3: 321 in-tree OK; 6258/6258 out-of-tree PASSED N=4: 321 in-tree OK; 15784/15784 out-of-tree PASSED Compiles clean with USE_TCCL=1.
66918c3 to
29f4b13
Compare
|
Hi sorry, missed this. Is this something that has widespread usefulness in upstream torch or does it make more sense to ship it as a separate wheel/project using the new entry_point registration in distributed for backends? |
|
I found this mccl external repo: But it doesn't seem to cover our vllm-metal use case ... |
|
Hi @d4l3k @Isalia20 @khushi-411 Is distributed inference planned in pytorch-mps backend? From our vllm-metal's benchmarking, pytorch-mps performance is very close to mlx after pinning pytorch to #200181 But we found that distributed inference is missing in pytorch-mps. May I get some guidance from the pytorch team? |
TCCL - Thunderbolt Collective Communication Library
As of now, PyTorch has no MPS-native communication backend, so
torch.distributedcollectives do not run on Apple Silicon. We introduce TCCL to fill that gap: a low-latency communication backend (c10d::Backend) that runs collectives on MPS tensors over RDMA on Thunderbolt 5. It implements all necessary collectives to enable parallelism strategies available on the front-end.Requirements. macOS 26.2 and Thunderbolt 5 hardware.
Design
TCCL is an in-tree
c10d::Backend, functionally inspired by JACCL and structurally modelled around NCCL for PyTorch integration.The transport layer utilizes RDMA (Remote Direct Memory Access). RDMA bypasses the OS kernel - up to an order of magnitude lower latency and higher bandwidth than TCP.
On fp32, TCCL cuts small-message latency ~56× and reaches ~7.6 GB/s per rank of effective bandwidth.
Implementation
TCCL is implemented in 3 main files. A few more files wire the distributed-on-MPS path. Tests are covered below.
ProcessGroupTCCL.{hpp,cpp}c10d::Backendsubclass (Options,TCCLWork); 12-step RDMA bootstrap ctor, workerrunLoop,enqueueCollectiveasync scaffold, all collective overrides, and the reduce-op / dtype / mesh-vs-ring dispatch.TCCLUtils.{hpp,cpp}dlopenlibrdma + dlsym (TCCLIBVWrapper), UC queue-pair lifecycle (INIT→RTR→RTS, post/poll) (TCCLConnection), registered staging buffers (TCCLSharedBuffer),TCCLDestination, link-layer subnet check, Store bootstrap.ProcessGroupTCCLDetail.{hpp,ipp}__bf16add);kChunkSize; the sharedmesh_exchange,ring_step, andbidir_ring_stepprimitives (depth-2 pipelined); every mesh + ring collective;wr_idencoding.Collectives
The full set for every exposed parallelism strategy. Most run in ring and mesh.
gatherandscatterare mesh-only.allreducereducebroadcastallgather(list)_allgather_baseallgather_into_tensor_coalescedgatherscatterreduce_scatter(list)_reduce_scatter_basereduce_scatter_tensor_coalescedalltoall_basesend/recvbarrierAlgorithm selection
Selection is dynamic, by node count and payload. Benchmarks show allreduce wins with ring even on a mesh at N={3,4}.
Compute-communication overlap
RDMA is a kernel-bypass, CPU-side API. Each collective runs on a dedicated CPU worker: it drives the RDMA, polls completions, and reduces, while the NIC DMAs the payload over Thunderbolt 5.
Overlap comes from the offload. PyTorch MPS Backend exposes a single serial stream, so a collective cannot hide behind compute on a second GPU stream - but the CPU worker runs it while the GPU stays busy. The hand-off is an
MTLSharedEvent: the main thread records a signal (non-blocking, via commit-and-continue), the worker waits on it. The GPU is never drained.Evaluation
Measured on 4× Mac mini M4 Pro (48/48/64/64 GB), clustered all-to-all over Thunderbolt 5. N<4 and ring runs use a subset of the machines and connections.
Correctness
319 in-tree cases across three test classes:
allreduce;reduce(rooted, non-zero root);broadcast;allgather(list,_allgather_base, DTensor/TP coalesced);gather/scatter(rooted, non-zero root, mesh-only reject on ring);reduce_scatter(list,_reduce_scatter_base/ FSDP, coalesced);alltoall_base(equal, unevenalltoallv, multi-chunk);send/recv(chain, directed pair, multi-chunk, non-adjacent);barrier.send/recv, a 12 MBallreducethat trips the ≥ 1 MB ring auto-switch, and ragged odd sizes (N full chunks + 1 element) forced onto the ringAn out-of-tree superset (which we used for development) adds a full shape sweep, a memory-layout axis (contiguous, sliced, transposed, narrowed, reshaped, chunk-output views with non-zero storage offset), float64, and broader campaigns - ring-vs-mesh sweeps, UC sustained-load stress, raw-RDMA and collective microbenchmarks, and LLM TP/PP scaling on real models.
Example workloads
FLUX.1-dev, 4 nodes vs one - DDP LoRA fine-tune (training throughput) and TP inference (denoising latency).
TCCL is otherwise use-case-agnostic - any
torch.distributedworkload with front-end MPS support runs over it. We have run LLMs (Qwen, Llama, ...) in TP and PP inference; TP=4 reaches ~2.3× decode throughput at large batch.The broader point is enablement: sharding runs models that exceed a single node's memory directly in PyTorch on Apple Silicon - previously not an option.
Running TCCL
TCCL needs three things:
The backend reads everything from env vars plus the standard rendezvous.
Spelled-out setup for 2-/4-node
1. One-time per node
Enable RDMA on every node (Recovery Mode, then reboot): https://developer.apple.com/documentation/technotes/tn3205-low-latency-communication-with-rdma-over-thunderbolt
2. Per boot / node
Give each Thunderbolt cable a static IP. Every cable is its own
/30subnet, and the two ends get different addresses (conventionally.1and.2- not always.1). The only hard rule: both ends of a cable share a non-link-local/30. These IPs just bring the RDMA link up; data never leaves the cable.A node has one interface (and one
/30) per cable - a 2-node setup has one, a 4-node full mesh has three per node. WhichenXreaches which peer is just how the cables are plugged in.3. Launch
Example A - 2 nodes (
amadeus= rank 0,ludwig= rank 1, cableden2↔en2):TCCL_DEVICEnames the RDMA device (omit it if the node exposes exactly one).Example B - 4 nodes, full mesh (
amadeus,ludwig,johann,joseph). Each Mac's 3 Thunderbolt ports connect it to every other node, so each configures 3 cables (each its own/30) and setsTCCL_PEER_DEVICESinstead ofTCCL_DEVICE: a comma-separated list of lengthWORLD_SIZEgiving the device this rank uses to reach each peer, own slot empty.MASTER_ADDRis rank 0's IP on the caller's cable (rank 0's store binds all interfaces).MASTER_ADDRdiffers per rank - rank 2 reaches rank 0 over the192.168.13.xcable, rank 3 over192.168.14.x. If the nodes also share a routable network (LAN/IPv6), use one sharedMASTER_ADDRfor all ranks; the per-cable IPs above are what make it work Thunderbolt-only / offline.4. In your PyTorch script
Addressing and the
enXmapping are per-cable and come from how things are plugged in - a discovery script can generate both the subnet setup and theTCCL_PEER_DEVICESrows, but the backend only needs the env vars above.5. Check setup before launching
Future work