opt.py 2.3 KB
Newer Older
1
2
3
import torch
import torch.distributed

4
from typing import Optional
5
6
7
8
9

from transformers import (
    AutoTokenizer,
    AutoConfig,
)
10
from text_generation_server.models.custom_modeling.opt_modeling import OPTForCausalLM
11
12
13
14
from text_generation_server.models import CausalLM
from text_generation_server.utils import (
    initialize_torch_distributed,
    weight_files,
15
    Weights,
16
17
18
)


19
class OPTSharded(CausalLM):
20
    def __init__(
21
22
23
24
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
25
        trust_remote_code: bool = False,
26
    ):
27
        self.process_group, rank, world_size = initialize_torch_distributed()
28
        if torch.cuda.is_available():
29
            device = torch.device(f"cuda:{rank}")
30
            dtype = torch.float16
31
32
33
34
35
        else:
            device = torch.device("cpu")
            dtype = torch.float32

        tokenizer = AutoTokenizer.from_pretrained(
36
37
38
39
40
            model_id,
            revision=revision,
            padding_side="left",
            truncation_side="left",
            trust_remote_code=trust_remote_code,
41
42
43
        )

        config = AutoConfig.from_pretrained(
44
45
46
            model_id,
            revision=revision,
            trust_remote_code=trust_remote_code,
47
        )
48
        config.quantize = quantize
49
50
51
52
        tokenizer.pad_token_id = config.pad_token_id

        torch.distributed.barrier(group=self.process_group)
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
53
54
55
        weights = Weights(
            filenames, device=device, dtype=dtype, process_group=self.process_group
        )
56

57
        model = OPTForCausalLM(config, weights)
58
59
60

        torch.distributed.barrier(group=self.process_group)
        super(CausalLM, self).__init__(
61
            model=model,
62
            tokenizer=tokenizer,
63
64
            requires_padding=True,
            dtype=dtype,
65
            device=device,
66
67
            rank=rank,
            world_size=world_size,
68
69
70
71
72
73
74
75
76
77
78
79
        )

    def forward(
        self, input_ids, attention_mask, position_ids, past_key_values: Optional = None
    ):
        outputs = self.model.forward(
            input_ids=input_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            use_cache=True,
        )

80
        return outputs.logits, outputs.past_key_values