model.py 3.57 KB
Newer Older
1
import inspect
2
3
import torch

4
from abc import ABC, abstractmethod
5
from typing import List, Tuple, Optional, TypeVar, Type
6
from transformers import PreTrainedTokenizerBase, PretrainedConfig
7

8
from text_generation_server.models.types import Batch, Generation
9
from text_generation_server.pb.generate_pb2 import InfoResponse
10

11
12
B = TypeVar("B", bound=Batch)

13

14
class Model(ABC):
15
16
    def __init__(
        self,
17
        model: torch.nn.Module,
18
        tokenizer: PreTrainedTokenizerBase,
19
20
        requires_padding: bool,
        dtype: torch.dtype,
21
        device: torch.device,
22
23
        rank: int = 0,
        world_size: int = 1,
24
        sliding_window: Optional[int] = None,
25
    ):
26
        self.model = model.eval()
27
        self.tokenizer = tokenizer
28
        self.all_special_ids = set(tokenizer.all_special_ids)
29
30
        self.requires_padding = requires_padding
        self.dtype = dtype
31
        self.device = device
32
33
        self.rank = rank
        self.world_size = world_size
34
        self.sliding_window = sliding_window
35
36
37
38
39
40

        self.has_position_ids = (
            inspect.signature(model.forward).parameters.get("position_ids", None)
            is not None
        )

41
        self.check_initialized()
42

43
44
    @property
    def info(self) -> InfoResponse:
45
46
47
        if self.requires_padding and self.sliding_window is not None:
            raise NotImplementedError("sliding_window is not implemented with padding")

48
49
50
51
        return InfoResponse(
            requires_padding=self.requires_padding,
            dtype=str(self.dtype),
            device_type=self.device.type,
52
            window_size=self.sliding_window,
53
54
        )

55
    @property
56
    @abstractmethod
57
    def batch_type(self) -> Type[B]:
58
        raise NotImplementedError
59

60
    @abstractmethod
61
    def generate_token(self, batch: B) -> Tuple[List[Generation], Optional[B]]:
62
        raise NotImplementedError
63

64
    def warmup(self, batch: B) -> Optional[int]:
65
        self.generate_token(batch)
66
        return None
67

68
69
70
    def decode_token(
        self,
        all_input_ids: List[int],
71
72
        prefix_offset: int = 0,
        read_offset: int = 0,
73
        skip_special_tokens: bool = False,
74
    ) -> Tuple[str, int, int]:
75
        """Hack to hopefully support generate_stream for the maximum number of tokenizers"""
76

77
78
79
        # The prefix text is necessary only to defeat cleanup algorithms in the decode
        # which decide to add a space or not depending on the surrounding ids.
        prefix_text = self.tokenizer.decode(
OlivierDehaene's avatar
OlivierDehaene committed
80
81
            all_input_ids[prefix_offset:read_offset],
            skip_special_tokens=skip_special_tokens,
82
83
        )
        new_text = self.tokenizer.decode(
84
            all_input_ids[prefix_offset:], skip_special_tokens=skip_special_tokens
85
        )
86

87
88
89
90
91
92
93
        if len(new_text) > len(prefix_text) and not new_text.endswith("�"):
            # utf-8 char at the end means it's a potential unfinished byte sequence
            # from byte fallback tokenization.
            # If it's in the middle, it's probably a real invalid id generated
            # by the model
            new_text = new_text[len(prefix_text) :]
            return new_text, read_offset, len(all_input_ids)
94
        else:
95
            return "", prefix_offset, read_offset
96
97
98
99
100
101
102
103
104
105

    def check_initialized(self):
        uninitialized_parameters = []
        for n, p in self.model.named_parameters():
            if p.data.device == torch.device("meta"):
                uninitialized_parameters.append(n)
        if uninitialized_parameters:
            raise RuntimeError(
                f"found uninitialized parameters in model {self.__class__.__name__}: {uninitialized_parameters}"
            )