Skip to content

vllm.distributed.device_communicators.pynccl

Classes:

PyNcclCommunicator

Methods:

  • __init__ –

    Args:

  • resume –

    Restore resources released by suspend().

  • suspend –

    Temporarily release this communicator's dynamic GPU resources.

Source code in vllm/distributed/device_communicators/pynccl.py
 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
class PyNcclCommunicator:
    def __init__(
        self,
        group: ProcessGroup | StatelessProcessGroup,
        device: int | str | torch.device,
        library_path: str | None = None,
    ):
        """
        Args:
            group: the process group to work on. If None, it will use the
                default process group.
            device: the device to bind the PyNcclCommunicator to. If None,
                it will be bound to f"cuda:{local_rank}".
            library_path: the path to the NCCL library. If None, it will
                use the default library path.
        It is the caller's responsibility to make sure each communicator
        is bind to a unique device.
        """
        if not isinstance(group, StatelessProcessGroup):
            assert dist.is_initialized()
            assert dist.get_backend(group) != dist.Backend.NCCL, (
                "PyNcclCommunicator should be attached to a non-NCCL group."
            )
            # note: this rank is the rank in the group
            self.rank = dist.get_rank(group)
            self.world_size = dist.get_world_size(group)
        else:
            self.rank = group.rank
            self.world_size = group.world_size

        self.group = group

        # if world_size == 1, no need to create communicator
        if self.world_size == 1 or envs.VLLM_DISABLE_PYNCCL:
            self.available = False
            self.disabled = True
            return
        try:
            self.nccl = NCCLLibrary(library_path)
        except Exception:
            # disable because of missing NCCL library
            # e.g. in a non-GPU environment
            self.available = False
            self.disabled = True
            return

        self.available = True
        self.disabled = False
        self.suspended = False

        self.nccl_version = self.nccl.ncclGetRawVersion()
        if self.rank == 0:
            # get the unique id from NCCL
            self.unique_id = self.nccl.ncclGetUniqueId()
            logger.info_once("vLLM is using nccl==%s", self.nccl.ncclGetVersion())
        else:
            # construct an empty unique id
            self.unique_id = ncclUniqueId()

        if not isinstance(group, StatelessProcessGroup):
            tensor = torch.ByteTensor(list(self.unique_id.internal))
            ranks = dist.get_process_group_ranks(group)
            # arg `src` in `broadcast` is the global rank
            dist.broadcast(tensor, src=ranks[0], group=group)
            byte_list = tensor.tolist()
            for i, byte in enumerate(byte_list):
                self.unique_id.internal[i] = byte
        else:
            self.unique_id = group.broadcast_obj(self.unique_id, src=0)
        if isinstance(device, int):
            device = torch.device(f"cuda:{device}")
        elif isinstance(device, str):
            device = torch.device(device)
        # now `device` is a `torch.device` object
        assert isinstance(device, torch.device)
        self.device = device
        # nccl communicator and stream will use this device
        with torch.accelerator.device_index(device.index):
            free_before, _ = torch.cuda.mem_get_info(device.index)
            self.comm: ncclComm_t = self.nccl.ncclCommInitRank(
                self.world_size, self.unique_id, self.rank
            )
            free_after_init, _ = torch.cuda.mem_get_info(device.index)

            stream = current_stream()
            # A small all_reduce for warmup.
            data = torch.zeros(1, device=device)
            self.all_reduce(data)
            stream.synchronize()
            del data
            free_after_warmup, _ = torch.cuda.mem_get_info(device.index)
            logger.info(
                "NCCL comm (world_size=%d) non-torch memory: commInitRank=%.1f "
                "MiB, channel buffers (first all_reduce)=%.1f MiB, total=%.1f "
                "MiB",
                self.world_size,
                (free_before - free_after_init) / (1024**2),
                (free_after_init - free_after_warmup) / (1024**2),
                (free_before - free_after_warmup) / (1024**2),
            )

    @classmethod
    def _from_existing_comm(
        cls,
        parent: "PyNcclCommunicator",
        comm: ncclComm_t,
    ) -> "PyNcclCommunicator":
        self = cls.__new__(cls)
        self.group = parent.group
        self.nccl = parent.nccl
        self.nccl_version = parent.nccl_version
        self.comm = comm
        self.rank = self.nccl.ncclCommUserRank(comm)
        self.world_size = self.nccl.ncclCommCount(comm)
        self.device = parent.device
        self.available = True
        self.disabled = False
        self.suspended = False
        return self

    def split(
        self, color: int | None, key: int | None = None
    ) -> "PyNcclCommunicator | None":
        if self.disabled:
            return None
        assert not self.suspended, (
            "cannot split a suspended NCCL communicator; call resume() first"
        )
        if color is None:
            color = NCCL_SPLIT_NOCOLOR
        elif color < 0:
            raise ValueError("color must be non-negative or None")
        if key is None:
            key = self.rank

        with torch.accelerator.device_index(self.device.index):
            comm = self.nccl.ncclCommSplit(self.comm, color, key)
        if comm is None:
            return None
        return self._from_existing_comm(self, comm)

    @property
    def supports_suspend(self) -> bool:
        return self.available and not self.disabled and self.nccl.hasCommSuspend()

    def suspend(self, flags: int = NCCL_SUSPEND_MEM) -> bool:
        """Temporarily release this communicator's dynamic GPU resources.

        The communicator handle stays valid but must not issue any
        communication until `resume()` is called. Requires an NCCL build
        with the ncclCommSuspend extension; returns False (no-op) otherwise.
        """
        if not self.supports_suspend or self.suspended:
            return False
        with torch.accelerator.device_index(self.device.index):
            free_before, _ = torch.cuda.mem_get_info(self.device.index)
            self.nccl.ncclCommSuspend(self.comm, flags)
            free_after, _ = torch.cuda.mem_get_info(self.device.index)
        self.suspended = True
        logger.info(
            "Suspended NCCL comm (world_size=%d), freed %.1f MiB",
            self.world_size,
            (free_after - free_before) / (1024**2),
        )
        return True

    def resume(self) -> bool:
        """Restore resources released by `suspend()`."""
        if not self.suspended:
            return False
        with torch.accelerator.device_index(self.device.index):
            self.nccl.ncclCommResume(self.comm)
        self.suspended = False
        logger.info("Resumed NCCL comm (world_size=%d)", self.world_size)
        return True

    def destroy(self):
        if self.available and not self.disabled:
            # ncclCommAbort can block until all CUDA graphs that
            # captured NCCL ops on this comm are destroyed — and
            # those graphs are released later in this same main-
            # thread teardown, so a direct call here self-deadlocks.
            # Run it in a daemon thread with a timeout: the main
            # thread proceeds, the graphs drop, and the abort returns.
            def _abort():
                with torch.accelerator.device_index(self.device.index):
                    self.nccl.ncclCommAbort(self.comm)

            abort_thread = threading.Thread(target=_abort, daemon=True)
            abort_thread.start()
            abort_thread.join(timeout=5.0)
            self.available = False
            self.disabled = True

    def all_reduce(
        self,
        in_tensor: torch.Tensor,
        out_tensor: torch.Tensor = None,
        op: ReduceOp = ReduceOp.SUM,
        stream=None,
    ) -> torch.Tensor:
        if self.disabled:
            return None
        # nccl communicator created on a specific device
        # will only work on tensors on the same device
        # otherwise it will cause "illegal memory access"
        assert in_tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {in_tensor.device}"
        )

        if out_tensor is None:
            out_tensor = torch.empty_like(in_tensor)

        if stream is None:
            stream = current_stream()
        self.nccl.ncclAllReduce(
            buffer_type(in_tensor.data_ptr()),
            buffer_type(out_tensor.data_ptr()),
            in_tensor.numel(),
            ncclDataTypeEnum.from_torch(in_tensor.dtype),
            ncclRedOpTypeEnum.from_torch(op),
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )
        return out_tensor

    def all_gather(
        self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, stream=None
    ):
        if self.disabled:
            return
        # nccl communicator created on a specific device
        # will only work on tensors on the same device
        # otherwise it will cause "illegal memory access"
        assert input_tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {input_tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        self.nccl.ncclAllGather(
            buffer_type(input_tensor.data_ptr()),
            buffer_type(output_tensor.data_ptr()),
            input_tensor.numel(),
            ncclDataTypeEnum.from_torch(input_tensor.dtype),
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )

    def all_gatherv(
        self,
        output_tensor: torch.Tensor,
        input_tensor: torch.Tensor,
        sizes: list[int],
        stream=None,
    ):
        if self.disabled:
            return
        # nccl communicator created on a specific device
        # will only work on tensors on the same device
        # otherwise it will cause "illegal memory access"
        assert input_tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {input_tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        assert output_tensor.shape[0] == sum(sizes)
        split_offset = 0
        self.nccl.ncclGroupStart()
        for root, split_size in enumerate(sizes):
            dst_slice = output_tensor[split_offset : split_offset + split_size]
            self.nccl.ncclBroadcast(
                buffer_type(input_tensor.data_ptr()),
                buffer_type(dst_slice.data_ptr()),
                dst_slice.numel(),
                ncclDataTypeEnum.from_torch(input_tensor.dtype),
                root,
                self.comm,
                cudaStream_t(stream.cuda_stream),
            )
            split_offset += split_size
        self.nccl.ncclGroupEnd()

    def reduce_scatter(
        self,
        output_tensor: torch.Tensor,
        input_tensor: torch.Tensor,
        op: ReduceOp = ReduceOp.SUM,
        stream=None,
    ):
        if self.disabled:
            return
        # nccl communicator created on a specific device
        # will only work on tensors on the same device
        # otherwise it will cause "illegal memory access"
        assert input_tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {input_tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        self.nccl.ncclReduceScatter(
            buffer_type(input_tensor.data_ptr()),
            buffer_type(output_tensor.data_ptr()),
            output_tensor.numel(),
            ncclDataTypeEnum.from_torch(input_tensor.dtype),
            ncclRedOpTypeEnum.from_torch(op),
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )

    def reduce_scatterv(
        self,
        output_tensor: torch.Tensor,
        input_tensor: torch.Tensor,
        sizes: list[int],
        op: ReduceOp = ReduceOp.SUM,
        stream=None,
    ):
        if self.disabled:
            return
        # nccl communicator created on a specific device
        # will only work on tensors on the same device
        # otherwise it will cause "illegal memory access"
        assert input_tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {input_tensor.device}"
        )
        if stream is None:
            stream = current_stream()

        split_offset = 0
        self.nccl.ncclGroupStart()
        for root, split_size in enumerate(sizes):
            chunk = input_tensor[split_offset : split_offset + split_size, ...]
            self.nccl.ncclReduce(
                buffer_type(chunk.data_ptr()),
                buffer_type(output_tensor.data_ptr()),
                chunk.numel(),
                ncclDataTypeEnum.from_torch(input_tensor.dtype),
                ncclRedOpTypeEnum.from_torch(op),
                root,
                self.comm,
                cudaStream_t(stream.cuda_stream),
            )
            split_offset += split_size
        self.nccl.ncclGroupEnd()

    def send(self, tensor: torch.Tensor, dst: int, stream=None):
        if self.disabled:
            return
        assert tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        if tensor.dtype in [
            torch.float8_e5m2,
            torch.float8_e4m3fn,
            torch.float8_e4m3fnuz,
            torch.float8_e5m2fnuz,
        ]:
            nccl_dtype = ncclDataTypeEnum.from_torch(torch.uint8)
        else:
            nccl_dtype = ncclDataTypeEnum.from_torch(tensor.dtype)
        self.nccl.ncclSend(
            buffer_type(tensor.data_ptr()),
            tensor.numel(),
            nccl_dtype,
            dst,
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )

    def recv(self, tensor: torch.Tensor, src: int, stream=None):
        if self.disabled:
            return
        assert tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        if tensor.dtype in [
            torch.float8_e5m2,
            torch.float8_e4m3fn,
            torch.float8_e4m3fnuz,
            torch.float8_e5m2fnuz,
        ]:
            nccl_dtype = ncclDataTypeEnum.from_torch(torch.uint8)
        else:
            nccl_dtype = ncclDataTypeEnum.from_torch(tensor.dtype)
        self.nccl.ncclRecv(
            buffer_type(tensor.data_ptr()),
            tensor.numel(),
            nccl_dtype,
            src,
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )

    def broadcast(self, tensor: torch.Tensor, src: int, stream=None):
        if self.disabled:
            return
        assert tensor.device == self.device, (
            f"this nccl communicator is created to work on {self.device}, "
            f"but the input tensor is on {tensor.device}"
        )
        if stream is None:
            stream = current_stream()
        if src == self.rank:
            sendbuff = buffer_type(tensor.data_ptr())
            # NCCL requires the sender also to have a receive buffer
            recvbuff = buffer_type(tensor.data_ptr())
        else:
            sendbuff = buffer_type()
            recvbuff = buffer_type(tensor.data_ptr())
        self.nccl.ncclBroadcast(
            sendbuff,
            recvbuff,
            tensor.numel(),
            ncclDataTypeEnum.from_torch(tensor.dtype),
            src,
            self.comm,
            cudaStream_t(stream.cuda_stream),
        )

    def group_start(self):
        self.nccl.ncclGroupStart()

    def group_end(self):
        self.nccl.ncclGroupEnd()

    def register_comm_window(self, tensor: torch.Tensor):
        return self.nccl.ncclCommWindowRegister(
            self.comm,
            buffer_type(tensor.data_ptr()),
            tensor.numel() * tensor.element_size(),
            1,
        )

    def register_comm_window_raw(self, ptr: int, size: int):
        return self.nccl.ncclCommWindowRegister(self.comm, buffer_type(ptr), size, 1)

    def deregister_comm_window(self, window):
        return self.nccl.ncclCommWindowDeregister(self.comm, window)

    def batch_isend_irecv(self, p2p_ops: list, stream=None):
        if self.disabled:
            return
        if stream is None:
            stream = current_stream()
        self.group_start()
        for op in p2p_ops:
            if op.op is torch.distributed.isend:
                self.send(op.tensor, op.group_peer, stream)
            elif op.op is torch.distributed.irecv:
                self.recv(op.tensor, op.group_peer, stream)

        self.group_end()

__init__(group, device, library_path=None)

Parameters:

  • group

    (ProcessGroup | StatelessProcessGroup) –

    the process group to work on. If None, it will use the default process group.

  • device

    (int | str | device) –

    the device to bind the PyNcclCommunicator to. If None, it will be bound to f"cuda:{local_rank}".

  • library_path

    (str | None, default: None ) –

    the path to the NCCL library. If None, it will use the default library path.

It is the caller's responsibility to make sure each communicator is bind to a unique device.

Source code in vllm/distributed/device_communicators/pynccl.py
def __init__(
    self,
    group: ProcessGroup | StatelessProcessGroup,
    device: int | str | torch.device,
    library_path: str | None = None,
):
    """
    Args:
        group: the process group to work on. If None, it will use the
            default process group.
        device: the device to bind the PyNcclCommunicator to. If None,
            it will be bound to f"cuda:{local_rank}".
        library_path: the path to the NCCL library. If None, it will
            use the default library path.
    It is the caller's responsibility to make sure each communicator
    is bind to a unique device.
    """
    if not isinstance(group, StatelessProcessGroup):
        assert dist.is_initialized()
        assert dist.get_backend(group) != dist.Backend.NCCL, (
            "PyNcclCommunicator should be attached to a non-NCCL group."
        )
        # note: this rank is the rank in the group
        self.rank = dist.get_rank(group)
        self.world_size = dist.get_world_size(group)
    else:
        self.rank = group.rank
        self.world_size = group.world_size

    self.group = group

    # if world_size == 1, no need to create communicator
    if self.world_size == 1 or envs.VLLM_DISABLE_PYNCCL:
        self.available = False
        self.disabled = True
        return
    try:
        self.nccl = NCCLLibrary(library_path)
    except Exception:
        # disable because of missing NCCL library
        # e.g. in a non-GPU environment
        self.available = False
        self.disabled = True
        return

    self.available = True
    self.disabled = False
    self.suspended = False

    self.nccl_version = self.nccl.ncclGetRawVersion()
    if self.rank == 0:
        # get the unique id from NCCL
        self.unique_id = self.nccl.ncclGetUniqueId()
        logger.info_once("vLLM is using nccl==%s", self.nccl.ncclGetVersion())
    else:
        # construct an empty unique id
        self.unique_id = ncclUniqueId()

    if not isinstance(group, StatelessProcessGroup):
        tensor = torch.ByteTensor(list(self.unique_id.internal))
        ranks = dist.get_process_group_ranks(group)
        # arg `src` in `broadcast` is the global rank
        dist.broadcast(tensor, src=ranks[0], group=group)
        byte_list = tensor.tolist()
        for i, byte in enumerate(byte_list):
            self.unique_id.internal[i] = byte
    else:
        self.unique_id = group.broadcast_obj(self.unique_id, src=0)
    if isinstance(device, int):
        device = torch.device(f"cuda:{device}")
    elif isinstance(device, str):
        device = torch.device(device)
    # now `device` is a `torch.device` object
    assert isinstance(device, torch.device)
    self.device = device
    # nccl communicator and stream will use this device
    with torch.accelerator.device_index(device.index):
        free_before, _ = torch.cuda.mem_get_info(device.index)
        self.comm: ncclComm_t = self.nccl.ncclCommInitRank(
            self.world_size, self.unique_id, self.rank
        )
        free_after_init, _ = torch.cuda.mem_get_info(device.index)

        stream = current_stream()
        # A small all_reduce for warmup.
        data = torch.zeros(1, device=device)
        self.all_reduce(data)
        stream.synchronize()
        del data
        free_after_warmup, _ = torch.cuda.mem_get_info(device.index)
        logger.info(
            "NCCL comm (world_size=%d) non-torch memory: commInitRank=%.1f "
            "MiB, channel buffers (first all_reduce)=%.1f MiB, total=%.1f "
            "MiB",
            self.world_size,
            (free_before - free_after_init) / (1024**2),
            (free_after_init - free_after_warmup) / (1024**2),
            (free_before - free_after_warmup) / (1024**2),
        )

resume()

Restore resources released by suspend().

Source code in vllm/distributed/device_communicators/pynccl.py
def resume(self) -> bool:
    """Restore resources released by `suspend()`."""
    if not self.suspended:
        return False
    with torch.accelerator.device_index(self.device.index):
        self.nccl.ncclCommResume(self.comm)
    self.suspended = False
    logger.info("Resumed NCCL comm (world_size=%d)", self.world_size)
    return True

suspend(flags=NCCL_SUSPEND_MEM)

Temporarily release this communicator's dynamic GPU resources.

The communicator handle stays valid but must not issue any communication until resume() is called. Requires an NCCL build with the ncclCommSuspend extension; returns False (no-op) otherwise.

Source code in vllm/distributed/device_communicators/pynccl.py
def suspend(self, flags: int = NCCL_SUSPEND_MEM) -> bool:
    """Temporarily release this communicator's dynamic GPU resources.

    The communicator handle stays valid but must not issue any
    communication until `resume()` is called. Requires an NCCL build
    with the ncclCommSuspend extension; returns False (no-op) otherwise.
    """
    if not self.supports_suspend or self.suspended:
        return False
    with torch.accelerator.device_index(self.device.index):
        free_before, _ = torch.cuda.mem_get_info(self.device.index)
        self.nccl.ncclCommSuspend(self.comm, flags)
        free_after, _ = torch.cuda.mem_get_info(self.device.index)
    self.suspended = True
    logger.info(
        "Suspended NCCL comm (world_size=%d), freed %.1f MiB",
        self.world_size,
        (free_after - free_before) / (1024**2),
    )
    return True