models.py 2.74 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
from abc import ABC, abstractmethod
4
from typing import Any, Callable, Optional, TypeVar
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

from torch import nn

from vllm.logger import init_logger
from vllm.utils import LRUCache

logger = init_logger(__name__)


class AdapterModel(ABC):

    def __init__(self, model_id=None):
        self.id = model_id

    @abstractmethod
    def from_local_checkpoint(cls, model_dir, model_id=None, **kwargs):
        # Common initialization code
        # Load weights or embeddings from local checkpoint
        raise NotImplementedError("Subclasses must implement this method.")


T = TypeVar('T')


29
class AdapterLRUCache(LRUCache[int, T]):
30

31
    def __init__(self, capacity: int, deactivate_fn: Callable[[int], object]):
32
33
34
        super().__init__(capacity)
        self.deactivate_fn = deactivate_fn

35
    def _on_remove(self, key: int, value: Optional[T]):
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
        logger.debug("Removing adapter int id: %d", key)
        self.deactivate_fn(key)
        return super()._on_remove(key, value)


class AdapterModelManager(ABC):

    def __init__(
        self,
        model: nn.Module,
    ):
        """Create a AdapterModelManager and adapter for a given model.
        Args:
            model: the model to be adapted.
        """
        self.model: nn.Module = model
52
        self._registered_adapters: dict[int, Any] = {}
53
        # Dict instead of a Set for compatibility with LRUCache.
54
        self._active_adapters: dict[int, None] = {}
55
56
57
58
59
60
61
62
        self.adapter_type = 'Adapter'
        self._last_mapping = None

    def __len__(self) -> int:
        return len(self._registered_adapters)

    @property
    @abstractmethod
63
64
    def adapter_slots(self) -> int:
        raise NotImplementedError
65
66
67

    @property
    @abstractmethod
68
69
    def capacity(self) -> int:
        raise NotImplementedError
70
71
72

    @abstractmethod
    def activate_adapter(self, adapter_id: int) -> bool:
73
        raise NotImplementedError
74
75
76

    @abstractmethod
    def deactivate_adapter(self, adapter_id: int) -> bool:
77
        raise NotImplementedError
78
79
80

    @abstractmethod
    def add_adapter(self, adapter: Any) -> bool:
81
        raise NotImplementedError
82
83
84

    @abstractmethod
    def set_adapter_mapping(self, mapping: Any) -> None:
85
        raise NotImplementedError
86
87
88

    @abstractmethod
    def remove_adapter(self, adapter_id: int) -> bool:
89
        raise NotImplementedError
90
91

    @abstractmethod
92
93
    def remove_all_adapters(self) -> None:
        raise NotImplementedError
94
95
96

    @abstractmethod
    def get_adapter(self, adapter_id: int) -> Optional[Any]:
97
        raise NotImplementedError
98
99

    @abstractmethod
100
    def list_adapters(self) -> dict[int, Any]:
101
        raise NotImplementedError
102
103
104

    @abstractmethod
    def pin_adapter(self, adapter_id: int) -> bool:
105
        raise NotImplementedError