utils.py 3.12 KB
Newer Older
1
from collections import OrderedDict
2
from collections.abc import Sequence
3
from contextlib import contextmanager
4
5
from typing import (Any, Generic, Iterator, List, Optional, TypeVar, Union,
                    overload)
6
7
8
9
10
11

import zmq

from vllm.logger import init_logger

logger = init_logger(__name__)
12
13
14
15

T = TypeVar("T")


16
class ConstantList(Generic[T], Sequence):
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

    def __init__(self, x: List[T]) -> None:
        self._x = x

    def append(self, item):
        raise Exception("Cannot append to a constant list")

    def extend(self, item):
        raise Exception("Cannot extend a constant list")

    def insert(self, item):
        raise Exception("Cannot insert into a constant list")

    def pop(self, item):
        raise Exception("Cannot pop from a constant list")

    def remove(self, item):
        raise Exception("Cannot remove from a constant list")

    def clear(self):
        raise Exception("Cannot clear a constant list")

39
40
41
42
43
44
    def index(self,
              item: T,
              start: int = 0,
              stop: Optional[int] = None) -> int:
        return self._x.index(item, start,
                             stop if stop is not None else len(self._x))
45
46

    @overload
47
    def __getitem__(self, item: int) -> T:
48
49
50
51
52
53
        ...

    @overload
    def __getitem__(self, s: slice, /) -> List[T]:
        ...

54
    def __getitem__(self, item: Union[int, slice]) -> Union[T, List[T]]:
55
56
57
        return self._x[item]

    @overload
58
    def __setitem__(self, item: int, value: T):
59
60
61
        ...

    @overload
62
    def __setitem__(self, s: slice, value: T, /):
63
64
        ...

65
    def __setitem__(self, item: Union[int, slice], value: Union[T, List[T]]):
66
67
68
69
70
71
72
73
74
75
76
77
78
        raise Exception("Cannot set item in a constant list")

    def __delitem__(self, item):
        raise Exception("Cannot delete item from a constant list")

    def __iter__(self):
        return iter(self._x)

    def __contains__(self, item):
        return item in self._x

    def __len__(self):
        return len(self._x)
79
80
81


@contextmanager
82
83
84
def make_zmq_socket(
        path: str,
        type: Any) -> Iterator[zmq.Socket]:  # type: ignore[name-defined]
85
86
    """Context manager for a ZMQ socket"""

87
    ctx = zmq.Context()  # type: ignore[attr-defined]
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    try:
        socket = ctx.socket(type)

        if type == zmq.constants.PULL:
            socket.connect(path)
        elif type == zmq.constants.PUSH:
            socket.bind(path)
        else:
            raise ValueError(f"Unknown Socket Type: {type}")

        yield socket

    except KeyboardInterrupt:
        logger.debug("Worker had Keyboard Interrupt.")

    finally:
        ctx.destroy(linger=0)
105
106


107
108
109
110
111
K = TypeVar('K')
V = TypeVar('V')


class LRUDictCache(Generic[K, V]):
112
113

    def __init__(self, size: int):
114
        self.cache: OrderedDict[K, V] = OrderedDict()
115
116
        self.size = size

117
    def get(self, key: K, default=None) -> V:
118
119
120
121
122
123
        if key not in self.cache:
            return default

        self.cache.move_to_end(key)
        return self.cache[key]

124
    def put(self, key: K, value: V):
125
126
127
128
        self.cache[key] = value
        self.cache.move_to_end(key)
        if len(self.cache) > self.size:
            self.cache.popitem(last=False)