models.py 2.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

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

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')


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

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

36
    def _on_remove(self, key: int, value: Optional[T]):
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
        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
53
        self._registered_adapters: dict[int, Any] = {}
54
        # Dict instead of a Set for compatibility with LRUCache.
55
        self._active_adapters: dict[int, None] = {}
56
57
58
59
60
61
62
63
        self.adapter_type = 'Adapter'
        self._last_mapping = None

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

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

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

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

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

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

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

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

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

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

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

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