utils.py 18.9 KB
Newer Older
1
2
"""Common utilities."""

Lianmin Zheng's avatar
Lianmin Zheng committed
3
import base64
4
import fcntl
5
import logging
6
import multiprocessing
Lianmin Zheng's avatar
Lianmin Zheng committed
7
8
9
import os
import random
import socket
10
import struct
Lianmin Zheng's avatar
Lianmin Zheng committed
11
import time
12
from importlib.metadata import PackageNotFoundError, version
Lianmin Zheng's avatar
Lianmin Zheng committed
13
from io import BytesIO
Lianmin Zheng's avatar
Lianmin Zheng committed
14
from typing import List, Optional
Lianmin Zheng's avatar
Lianmin Zheng committed
15
16

import numpy as np
17
import psutil
Lianmin Zheng's avatar
Lianmin Zheng committed
18
import requests
19
import rpyc
Lianmin Zheng's avatar
Lianmin Zheng committed
20
import torch
21
import triton
22
from fastapi.responses import JSONResponse
23
from packaging import version as pkg_version
24
from rpyc.utils.server import ThreadedServer
Lianmin Zheng's avatar
Lianmin Zheng committed
25
from starlette.middleware.base import BaseHTTPMiddleware
26

27
28
logger = logging.getLogger(__name__)

Lianmin Zheng's avatar
Lianmin Zheng committed
29

Liangsheng Yin's avatar
Liangsheng Yin committed
30
31
show_time_cost = False
time_infos = {}
Lianmin Zheng's avatar
Lianmin Zheng committed
32
33


Liangsheng Yin's avatar
Liangsheng Yin committed
34
35
36
37
def enable_show_time_cost():
    global show_time_cost
    show_time_cost = True

Lianmin Zheng's avatar
Lianmin Zheng committed
38

Liangsheng Yin's avatar
Liangsheng Yin committed
39
40
41
42
43
44
class TimeInfo:
    def __init__(self, name, interval=0.1, color=0, indent=0):
        self.name = name
        self.interval = interval
        self.color = color
        self.indent = indent
Lianmin Zheng's avatar
Lianmin Zheng committed
45

Liangsheng Yin's avatar
Liangsheng Yin committed
46
47
        self.acc_time = 0
        self.last_acc_time = 0
Lianmin Zheng's avatar
Lianmin Zheng committed
48

Liangsheng Yin's avatar
Liangsheng Yin committed
49
50
51
52
53
    def check(self):
        if self.acc_time - self.last_acc_time > self.interval:
            self.last_acc_time = self.acc_time
            return True
        return False
Lianmin Zheng's avatar
Lianmin Zheng committed
54

Liangsheng Yin's avatar
Liangsheng Yin committed
55
56
57
58
    def pretty_print(self):
        print(f"\x1b[{self.color}m", end="")
        print("-" * self.indent * 2, end="")
        print(f"{self.name}: {self.acc_time:.3f}s\x1b[0m")
Lianmin Zheng's avatar
Lianmin Zheng committed
59
60


Liangsheng Yin's avatar
Liangsheng Yin committed
61
62
63
64
def mark_start(name, interval=0.1, color=0, indent=0):
    global time_infos, show_time_cost
    if not show_time_cost:
        return
Lianmin Zheng's avatar
Lianmin Zheng committed
65
    torch.cuda.synchronize()
Liangsheng Yin's avatar
Liangsheng Yin committed
66
67
68
    if time_infos.get(name, None) is None:
        time_infos[name] = TimeInfo(name, interval, color, indent)
    time_infos[name].acc_time -= time.time()
Lianmin Zheng's avatar
Lianmin Zheng committed
69
70


Liangsheng Yin's avatar
Liangsheng Yin committed
71
72
73
74
def mark_end(name):
    global time_infos, show_time_cost
    if not show_time_cost:
        return
Lianmin Zheng's avatar
Lianmin Zheng committed
75
    torch.cuda.synchronize()
Liangsheng Yin's avatar
Liangsheng Yin committed
76
77
78
    time_infos[name].acc_time += time.time()
    if time_infos[name].check():
        time_infos[name].pretty_print()
Lianmin Zheng's avatar
Lianmin Zheng committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99


def calculate_time(show=False, min_cost_ms=0.0):
    def wrapper(func):
        def inner_func(*args, **kwargs):
            torch.cuda.synchronize()
            if show:
                start_time = time.time()
            result = func(*args, **kwargs)
            torch.cuda.synchronize()
            if show:
                cost_time = (time.time() - start_time) * 1000
                if cost_time > min_cost_ms:
                    print(f"Function {func.__name__} took {cost_time} ms to run.")
            return result

        return inner_func

    return wrapper


100
def get_available_gpu_memory(gpu_id, distributed=False):
Lianmin Zheng's avatar
Lianmin Zheng committed
101
102
103
104
105
106
107
108
109
110
111
112
113
    """
    Get available memory for cuda:gpu_id device.
    When distributed is True, the available memory is the minimum available memory of all GPUs.
    """
    num_gpus = torch.cuda.device_count()
    assert gpu_id < num_gpus

    if torch.cuda.current_device() != gpu_id:
        print(
            f"WARNING: current device is not {gpu_id}, but {torch.cuda.current_device()}, ",
            "which may cause useless memory allocation for torch CUDA context.",
        )

Lianmin Zheng's avatar
Lianmin Zheng committed
114
    torch.cuda.empty_cache()
Lianmin Zheng's avatar
Lianmin Zheng committed
115
116
117
118
119
120
121
122
123
124
125
126
    free_gpu_memory, _ = torch.cuda.mem_get_info(gpu_id)

    if distributed:
        tensor = torch.tensor(free_gpu_memory, dtype=torch.float32).to(
            torch.device("cuda", gpu_id)
        )
        torch.distributed.all_reduce(tensor, op=torch.distributed.ReduceOp.MIN)
        free_gpu_memory = tensor.item()

    return free_gpu_memory / (1 << 30)


Lianmin Zheng's avatar
Lianmin Zheng committed
127
def set_random_seed(seed: int) -> None:
128
    """Set the random seed for all libraries."""
Lianmin Zheng's avatar
Lianmin Zheng committed
129
    random.seed(seed)
130
    np.random.seed(seed)
Lianmin Zheng's avatar
Lianmin Zheng committed
131
132
133
134
135
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)


136
def is_port_available(port):
137
    """Return whether a port is available."""
138
139
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
140
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
141
            s.bind(("", port))
142
            s.listen(1)
143
144
145
146
147
            return True
        except socket.error:
            return False


Lianmin Zheng's avatar
Lianmin Zheng committed
148
def allocate_init_ports(
Lianmin Zheng's avatar
Lianmin Zheng committed
149
150
151
    port: Optional[int] = None,
    additional_ports: Optional[List[int]] = None,
    tp_size: int = 1,
152
    dp_size: int = 1,
Lianmin Zheng's avatar
Lianmin Zheng committed
153
):
154
    """Allocate ports for all connections."""
155
156
157
158
159
160
161
162
    if additional_ports:
        ret_ports = [port] + additional_ports
    else:
        ret_ports = [port]

    ret_ports = list(set(x for x in ret_ports if is_port_available(x)))
    cur_port = ret_ports[-1] + 1 if len(ret_ports) > 0 else 10000

163
164
165
    # HTTP + Tokenizer + Controller + Detokenizer + dp_size * (nccl + tp_size)
    num_ports_needed = 4 + dp_size * (1 + tp_size)
    while len(ret_ports) < num_ports_needed:
166
167
168
169
        if cur_port not in ret_ports and is_port_available(cur_port):
            ret_ports.append(cur_port)
        cur_port += 1

170
    if port is not None and ret_ports[0] != port:
171
172
173
        logger.warn(
            f"WARNING: Port {port} is not available. Use port {ret_ports[0]} instead."
        )
Lianmin Zheng's avatar
Lianmin Zheng committed
174

175
    return ret_ports[0], ret_ports[1:num_ports_needed]
176

Lianmin Zheng's avatar
Lianmin Zheng committed
177

Lianmin Zheng's avatar
Lianmin Zheng committed
178
def get_int_token_logit_bias(tokenizer, vocab_size):
179
    """Get the logit bias for integer-only tokens."""
180
181
    # a bug when model's vocab size > tokenizer.vocab_size
    vocab_size = tokenizer.vocab_size
Lianmin Zheng's avatar
Lianmin Zheng committed
182
183
    logit_bias = np.zeros(vocab_size, dtype=np.float32)
    for t_id in range(vocab_size):
184
        ss = tokenizer.decode([t_id]).strip()
Lianmin Zheng's avatar
Lianmin Zheng committed
185
186
187
188
189
190
191
192
        if not (ss.isdigit() or len(ss) == 0 or t_id == tokenizer.eos_token_id):
            logit_bias[t_id] = -1e5

    return logit_bias


def wrap_kernel_launcher(kernel):
    """A faster launcher for triton kernels."""
193
194
    if int(triton.__version__.split(".")[0]) >= 3:
        return None
Lianmin Zheng's avatar
Lianmin Zheng committed
195

196
197
    gpu_id = torch.cuda.current_device()
    kernels = kernel.cache[gpu_id].values()
Lianmin Zheng's avatar
Lianmin Zheng committed
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
    kernel = next(iter(kernels))

    # Different trition versions use different low-level names
    if hasattr(kernel, "cu_function"):
        kfunction = kernel.cu_function
    else:
        kfunction = kernel.function

    if hasattr(kernel, "c_wrapper"):
        run = kernel.c_wrapper
    else:
        run = kernel.run

    add_cluster_dim = True

    def ret_func(grid, num_warps, *args):
        nonlocal add_cluster_dim

        try:
            if add_cluster_dim:
                run(
                    grid[0],
                    grid[1],
                    grid[2],
                    num_warps,
                    1,
                    1,
                    1,
                    1,
                    kernel.shared,
                    0,
                    kfunction,
                    None,
                    None,
                    kernel,
                    *args,
                )
            else:
                run(
                    grid[0],
                    grid[1],
                    grid[2],
                    num_warps,
                    kernel.shared,
                    0,
                    kfunction,
                    None,
                    None,
                    kernel,
                    *args,
                )
        except TypeError:
            add_cluster_dim = not add_cluster_dim
            ret_func(grid, num_warps, *args)

    return ret_func


def is_multimodal_model(model):
    from sglang.srt.model_config import ModelConfig

Yuanhan Zhang's avatar
Yuanhan Zhang committed
259
260
261
262
    if isinstance(model, str):
        model = model.lower()
        return "llava" in model or "yi-vl" in model or "llava-next" in model

Lianmin Zheng's avatar
Lianmin Zheng committed
263
    if isinstance(model, ModelConfig):
Christopher Chou's avatar
Christopher Chou committed
264
        model_path = model.path.lower()
Liangsheng Yin's avatar
Liangsheng Yin committed
265
266
267
        return (
            "llava" in model_path or "yi-vl" in model_path or "llava-next" in model_path
        )
Yuanhan Zhang's avatar
Yuanhan Zhang committed
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

    raise ValueError("unrecognized type")


def decode_video_base64(video_base64):
    from PIL import Image

    # Decode the base64 string
    video_bytes = base64.b64decode(video_base64)

    # Placeholder for the start indices of each PNG image
    img_starts = []

    frame_format = "PNG"  # str(os.getenv('FRAME_FORMAT', "JPEG"))

    assert frame_format in [
        "PNG",
        "JPEG",
    ], "FRAME_FORMAT must be either 'PNG' or 'JPEG'"

    if frame_format == "PNG":
        # Find each PNG start signature to isolate images
        i = 0
        while i < len(video_bytes) - 7:  # Adjusted for the length of the PNG signature
            # Check if we found the start of a PNG file
            if (
                video_bytes[i] == 0x89
                and video_bytes[i + 1] == 0x50
                and video_bytes[i + 2] == 0x4E
                and video_bytes[i + 3] == 0x47
                and video_bytes[i + 4] == 0x0D
                and video_bytes[i + 5] == 0x0A
                and video_bytes[i + 6] == 0x1A
                and video_bytes[i + 7] == 0x0A
            ):
                img_starts.append(i)
                i += 8  # Skip the PNG signature
            else:
                i += 1
    else:
        # Find each JPEG start (0xFFD8) to isolate images
        i = 0
        while (
            i < len(video_bytes) - 1
        ):  # Adjusted for the length of the JPEG SOI signature
            # Check if we found the start of a JPEG file
            if video_bytes[i] == 0xFF and video_bytes[i + 1] == 0xD8:
                img_starts.append(i)
                # Move to the next byte to continue searching for the next image start
                i += 2
            else:
                i += 1

    frames = []
    for start_idx in img_starts:
        # Assuming each image is back-to-back, the end of one image is the start of another
        # The last image goes until the end of the byte string
        end_idx = (
            img_starts[img_starts.index(start_idx) + 1]
            if img_starts.index(start_idx) + 1 < len(img_starts)
            else len(video_bytes)
        )
        img_bytes = video_bytes[start_idx:end_idx]

        # Convert bytes to a PIL Image
        img = Image.open(BytesIO(img_bytes))

        # Convert PIL Image to a NumPy array
        frame = np.array(img)

        # Append the frame to the list of frames
        frames.append(frame)

    # Ensure there's at least one frame to avoid errors with np.stack
    if frames:
        return np.stack(frames, axis=0), img.size
    else:
        return np.array([]), (
            0,
            0,
        )  # Return an empty array and size tuple if no frames were found
Lianmin Zheng's avatar
Lianmin Zheng committed
349
350
351
352
353


def load_image(image_file):
    from PIL import Image

Yuanhan Zhang's avatar
Yuanhan Zhang committed
354
    image = image_size = None
Lianmin Zheng's avatar
Lianmin Zheng committed
355
356
357
358
359
360
361
362

    if image_file.startswith("http://") or image_file.startswith("https://"):
        timeout = int(os.getenv("REQUEST_TIMEOUT", "3"))
        response = requests.get(image_file, timeout=timeout)
        image = Image.open(BytesIO(response.content))
    elif image_file.lower().endswith(("png", "jpg", "jpeg", "webp", "gif")):
        image = Image.open(image_file)
    elif image_file.startswith("data:"):
363
        image_file = image_file.split(",")[1]
Lianmin Zheng's avatar
Lianmin Zheng committed
364
        image = Image.open(BytesIO(base64.b64decode(image_file)))
Yuanhan Zhang's avatar
Yuanhan Zhang committed
365
366
367
    elif image_file.startswith("video:"):
        image_file = image_file.replace("video:", "")
        image, image_size = decode_video_base64(image_file)
Lianmin Zheng's avatar
Lianmin Zheng committed
368
369
370
    else:
        image = Image.open(BytesIO(base64.b64decode(image_file)))

Yuanhan Zhang's avatar
Yuanhan Zhang committed
371
    return image, image_size
372
373


374
def connect_rpyc_service(host, port):
375
376
377
378
379
380
381
382
383
    repeat_count = 0
    while repeat_count < 20:
        try:
            con = rpyc.connect(
                host,
                port,
                config={
                    "allow_public_attrs": True,
                    "allow_pickle": True,
384
                    "sync_request_timeout": 3600,
385
386
387
                },
            )
            break
388
        except ConnectionRefusedError as e:
389
390
391
            time.sleep(1)
        repeat_count += 1
    if repeat_count == 20:
392
        raise RuntimeError(f"Connect rpyc error: {e}")
393
394
395
396

    return con.root


397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def start_rpyc_service(service: rpyc.Service, port: int):
    t = ThreadedServer(
        service=service,
        port=port,
        protocol_config={
            "allow_public_attrs": True,
            "allow_pickle": True,
            "sync_request_timeout": 3600,
        },
    )
    t.logger.setLevel(logging.WARN)
    t.start()


def start_rpyc_service_process(service: rpyc.Service, port: int):
    proc = multiprocessing.Process(target=start_rpyc_service, args=(service, port))
413
    proc.start()
414
    return proc
415
416
417
418
419
420
421


def suppress_other_loggers():
    from vllm.logger import logger as vllm_default_logger

    vllm_default_logger.setLevel(logging.WARN)
    logging.getLogger("vllm.config").setLevel(logging.ERROR)
422
423
424
    logging.getLogger("vllm.distributed.device_communicators.pynccl").setLevel(
        logging.WARN
    )
Lianmin Zheng's avatar
Lianmin Zheng committed
425
426
    logging.getLogger("vllm.selector").setLevel(logging.WARN)
    logging.getLogger("vllm.utils").setLevel(logging.WARN)
427
428


429
430
431
432
433
434
435
436
437
def assert_pkg_version(pkg: str, min_version: str):
    try:
        installed_version = version(pkg)
        if pkg_version.parse(installed_version) < pkg_version.parse(min_version):
            raise Exception(
                f"{pkg} is installed with version {installed_version} which "
                f"is less than the minimum required version {min_version}"
            )
    except PackageNotFoundError:
Yuanhan Zhang's avatar
Yuanhan Zhang committed
438
439
440
        raise Exception(
            f"{pkg} with minimum required version {min_version} is not installed"
        )
Lianmin Zheng's avatar
Lianmin Zheng committed
441
442


443
444
445
446
447
448
449
450
451
452
453
def kill_parent_process():
    """Kill the parent process and all children of the parent process."""
    current_process = psutil.Process()
    parent_process = current_process.parent()
    children = current_process.children(recursive=True)
    for child in children:
        if child.pid != current_process.pid:
            os.kill(child.pid, 9)
    os.kill(parent_process.pid, 9)


454
def monkey_patch_vllm_p2p_access_check(gpu_id: int):
455
456
457
458
459
    """
    Monkey patch the slow p2p access check in vllm.
    NOTE: We assume the p2p access is always allowed, which can be wrong for some setups.
    """

460
461
462
463
464
    # TODO: need a better check than just dev str name match
    # compat: skip RTX 40 series as they do not have P2P feature and even checking for them may cause errors
    device_name = torch.cuda.get_device_name(gpu_id)
    if "RTX 40" not in device_name:
        import vllm.distributed.device_communicators.custom_all_reduce_utils as tgt
465

466
        setattr(tgt, "gpu_p2p_access_check", lambda *arg, **kwargs: True)
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
def monkey_patch_vllm_dummy_weight_loader():
    """
    Monkey patch the dummy weight loader in vllm to call process_weights_after_loading.
    """

    from vllm.model_executor.model_loader.loader import (
        ModelConfig, DeviceConfig, LoRAConfig, VisionLanguageConfig,
        ParallelConfig, SchedulerConfig, CacheConfig, nn,
        set_default_torch_dtype, _initialize_model, initialize_dummy_weights,
        DummyModelLoader
    )

    def load_model(self, *, model_config: ModelConfig,
                   device_config: DeviceConfig,
                   lora_config: Optional[LoRAConfig],
                   vision_language_config: Optional[VisionLanguageConfig],
                   parallel_config: ParallelConfig,
                   scheduler_config: SchedulerConfig,
                   cache_config: CacheConfig) -> nn.Module:
        with set_default_torch_dtype(model_config.dtype):
            with torch.device(device_config.device):
                model = _initialize_model(model_config, self.load_config,
                                          lora_config, vision_language_config,
                                          cache_config)

            for _, module in model.named_modules():
                quant_method = getattr(module, "quant_method", None)
                if quant_method is not None:
                    quant_method.process_weights_after_loading(module)
                # FIXME: Remove this after Mixtral is updated
                # to use quant_method.
                if hasattr(module, "process_weights_after_loading"):
                    module.process_weights_after_loading()

            # NOTE(woosuk): For accurate performance evaluation, we assign
            # random values to the weights.
            initialize_dummy_weights(model)
        return model.eval()

    setattr(DummyModelLoader, "load_model", load_model)


Lianmin Zheng's avatar
Lianmin Zheng committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
API_KEY_HEADER_NAME = "X-API-Key"


class APIKeyValidatorMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, api_key: str):
        super().__init__(app)
        self.api_key = api_key

    async def dispatch(self, request, call_next):
        # extract API key from the request headers
        api_key_header = request.headers.get(API_KEY_HEADER_NAME)
        if not api_key_header or api_key_header != self.api_key:
            return JSONResponse(
                status_code=403,
                content={"detail": "Invalid API Key"},
            )
        response = await call_next(request)
528
        return response
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


def get_ip_address(ifname):
    """
    Get the IP address of a network interface.

    :param ifname: Name of the network interface (e.g., 'eth0')
    :return: IP address of the network interface
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_address = fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', bytes(ifname[:15], 'utf-8'))
    )[20:24]
    return socket.inet_ntoa(ip_address)


def send_addrs_to_rank_0(model_port_args, server_args):
    assert server_args.node_rank != 0 and server_args.dp_size == 1
    import torch.distributed as dist

    ifname = os.environ.get("SGLANG_SOCKET_IFNAME", os.environ.get("NCCL_SOCKET_IFNAME", "eth0"))
    ip_addr = get_ip_address(ifname)

    num_tp_ports = server_args.tp_size // server_args.nnodes
    model_port_args.model_tp_ips[:num_tp_ports] = [ip_addr] * num_tp_ports
    ip_addr = [int(x) for x in ip_addr.split(".")]
    addrs_tensor = torch.tensor(ip_addr + model_port_args.model_tp_ports, dtype=torch.int)

    init_method = f"tcp://{server_args.nccl_init_addr}"
    dist.init_process_group(backend="gloo", init_method=init_method, rank=server_args.node_rank, world_size=server_args.nnodes)
    dist.send(addrs_tensor, dst=0)
    print(f"Node {server_args.node_rank} sent: ip_address {ip_addr} and ports {model_port_args.model_tp_ports}")

    dist.barrier()
    dist.destroy_process_group() 


def receive_addrs(model_port_args, server_args):
    assert server_args.node_rank == 0 and server_args.dp_size == 1
    import torch.distributed as dist

    ifname = os.environ.get("SGLANG_SOCKET_IFNAME", os.environ.get("NCCL_SOCKET_IFNAME", "eth0"))
    ip_addr = get_ip_address(ifname)

    num_tp_ports = server_args.tp_size // server_args.nnodes
    model_port_args.model_tp_ips[:num_tp_ports] = [ip_addr] * num_tp_ports

    init_method = f"tcp://{server_args.nccl_init_addr}"
    dist.init_process_group(backend="gloo", init_method=init_method, rank=server_args.node_rank, world_size=server_args.nnodes)

    for src_rank in range(1, server_args.nnodes):
        tensor = torch.zeros(4 + num_tp_ports, dtype=torch.int)
        dist.recv(tensor, src=src_rank)
        ip = ".".join([str(x) for x in tensor[:4].tolist()])
        ports = tensor[4:].tolist()
        model_port_args.model_tp_ips[num_tp_ports * src_rank: num_tp_ports * (src_rank + 1)] = [ip] * num_tp_ports
        model_port_args.model_tp_ports[num_tp_ports * src_rank: num_tp_ports * (src_rank + 1)] = ports
        print(f"Node 0 received from rank {src_rank}: {tensor.tolist()}")

    dist.barrier()
    dist.destroy_process_group()