t5.py 3.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
import torch
import torch.distributed

from typing import List, Optional, Tuple

from transformers import (
    AutoTokenizer,
    AutoConfig,
)

11
from text_generation_server.models import Seq2SeqLM
12
13
14
from text_generation_server.models.custom_modeling.t5_modeling import (
    T5ForConditionalGeneration,
)
15
from text_generation_server.utils import (
16
17
    initialize_torch_distributed,
    weight_files,
18
    Weights,
19
20
21
22
23
)


class T5Sharded(Seq2SeqLM):
    def __init__(
24
25
26
27
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
28
        dtype: Optional[torch.dtype] = None,
29
        trust_remote_code: bool = False,
30
    ):
31
        self.process_group, rank, world_size = initialize_torch_distributed()
32
        if torch.cuda.is_available():
33
            device = torch.device(f"cuda:{rank}")
34
            dtype = torch.float16 if dtype is None else dtype
35
36
        else:
            device = torch.device("cpu")
Wang, Yi's avatar
Wang, Yi committed
37
            dtype = torch.float32 if dtype is None else dtype
38

39
        config = AutoConfig.from_pretrained(
40
41
42
            model_id,
            revision=revision,
            trust_remote_code=trust_remote_code,
43
        )
44
        config.quantize = quantize
45

46
        tokenizer = AutoTokenizer.from_pretrained(
47
48
            model_id,
            revision=revision,
49
50
            padding_side="left",
            truncation_side="left",
51
            trust_remote_code=trust_remote_code,
52
53
54
55
56
        )
        tokenizer.bos_token_id = config.decoder_start_token_id

        torch.distributed.barrier(group=self.process_group)
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
57
        weights = Weights(
58
59
60
61
62
63
64
65
66
67
            filenames,
            device=device,
            dtype=dtype,
            process_group=self.process_group,
            aliases={
                "shared.weight": [
                    "encoder.embed_tokens.weight",
                    "decoder.embed_tokens.weight",
                ]
            },
68
        )
69

70
        model = T5ForConditionalGeneration(config, weights)
71
72
73

        torch.distributed.barrier(group=self.process_group)
        super(Seq2SeqLM, self).__init__(
74
            model=model,
75
            tokenizer=tokenizer,
76
77
            requires_padding=True,
            dtype=dtype,
78
            device=device,
79
80
            rank=rank,
            world_size=world_size,
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
        )

    def forward(
        self,
        input_ids,
        attention_mask,
        decoder_input_ids,
        decoder_attention_mask: Optional,
        encoder_last_hidden_state: Optional,
        past_key_values: Optional = None,
    ) -> Tuple[
        torch.Tensor,
        torch.Tensor,
        List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]],
    ]:
        # Model Forward
        outputs = self.model.forward(
            input_ids=input_ids,
            attention_mask=attention_mask,
            decoder_input_ids=decoder_input_ids,
            decoder_attention_mask=decoder_attention_mask,
            encoder_outputs=encoder_last_hidden_state,
            past_key_values=past_key_values,
            use_cache=True,
        )

        return (
108
            outputs.logits,
109
110
111
            outputs.encoder_last_hidden_state,
            outputs.past_key_values,
        )