KatInterview

Rank Synchronization in PyTorch Distributed: How barrier() Works

System DesignModel answer
MediumModel answerSystem Designpytorchdistributed-trainingsynchronization

Last updated

Explain what a collective barrier does in PyTorch distributed training, how it is implemented per backend, when to use it, and how misuse causes hangs or wasted throughput.

You are running a multi-GPU training job in which several processes (ranks) each drive one device. A teammate asks you to review code that calls torch.distributed.barrier() in several places.

Answer the following as you would in a technical discussion:

  1. What does torch.distributed.barrier() guarantee, and what does it deliberately not do?
  2. How is it carried out under the hood on different backends (for example Gloo versus NCCL), and why does the device selection matter for NCCL?
  3. What does it cost, both in communication and in wall-clock time?
  4. Give a realistic usage pattern, such as having one rank prepare data or write a checkpoint while the others wait. Show the code.
  5. Describe the ways it can be misused: hangs, mismatched collective order, wrong device, and false assumptions about what it guarantees. Explain how you would debug a job that stalls at a barrier.
  6. When should you avoid it, for instance inside the inner training loop?

Aim for a structured answer that includes concrete trade-offs and common pitfalls.

Hints

Hint 1

Think of it as a rendezvous point: what must be true of every member of the process group before any member can continue, and is any tensor data exchanged?

Hint 2

Consider how a backend without a native barrier could emulate one, and what that implies about which GPU the operation runs on and what work it does or does not wait for.

Hint 3

Ask what happens if only some ranks reach the call, or if ranks issue different collectives in different orders, and which tools exist to find the rank that never arrived.