utils.py 1.62 KB
Newer Older
Woosuk Kwon's avatar
Woosuk Kwon committed
1
import enum
2
import os
3
import socket
Zhuohan Li's avatar
Zhuohan Li committed
4
import uuid
5
from platform import uname
6
from typing import List
Zhuohan Li's avatar
Zhuohan Li committed
7

8
import psutil
Zhuohan Li's avatar
Zhuohan Li committed
9
10
import torch

11
from vllm._C import cuda_utils
12

Woosuk Kwon's avatar
Woosuk Kwon committed
13
14
15
16
17
18
19
20
21
22
23

class Device(enum.Enum):
    GPU = enum.auto()
    CPU = enum.auto()


class Counter:

    def __init__(self, start: int = 0) -> None:
        self.counter = start

Woosuk Kwon's avatar
Woosuk Kwon committed
24
    def __next__(self) -> int:
25
        i = self.counter
Woosuk Kwon's avatar
Woosuk Kwon committed
26
        self.counter += 1
27
        return i
Woosuk Kwon's avatar
Woosuk Kwon committed
28
29
30

    def reset(self) -> None:
        self.counter = 0
Zhuohan Li's avatar
Zhuohan Li committed
31

32

33
34
35
36
def is_hip() -> bool:
    return torch.version.hip is not None


37
38
39
def get_max_shared_memory_bytes(gpu: int = 0) -> int:
    """Returns the maximum shared memory per thread block in bytes."""
    # https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html
40
    cudaDevAttrMaxSharedMemoryPerBlockOptin = 97 if not is_hip() else 74
41
42
43
44
45
    max_shared_mem = cuda_utils.get_device_attribute(
        cudaDevAttrMaxSharedMemoryPerBlockOptin, gpu)
    return int(max_shared_mem)


46
def get_cpu_memory() -> int:
47
    """Returns the total CPU memory of the node in bytes."""
48
    return psutil.virtual_memory().total
Zhuohan Li's avatar
Zhuohan Li committed
49
50
51
52


def random_uuid() -> str:
    return str(uuid.uuid4().hex)
53

54

55
56
57
def in_wsl() -> bool:
    # Reference: https://github.com/microsoft/WSL/issues/4071
    return "microsoft" in " ".join(uname()).lower()
58
59


60
61
62
63
64
def get_ip() -> str:
    return socket.gethostbyname(socket.gethostname())


def get_open_port() -> int:
65
66
67
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("", 0))
        return s.getsockname()[1]
68
69
70
71


def set_cuda_visible_devices(device_ids: List[int]) -> None:
    os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, device_ids))