gpt_neox.py 2.57 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 import CausalLM
11
12
13
from text_generation_server.models.custom_modeling.neox_modeling import (
    GPTNeoxForCausalLM,
)
14
from text_generation_server.utils import (
15
16
    initialize_torch_distributed,
    weight_files,
17
    Weights,
18
19
20
)


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

        tokenizer = AutoTokenizer.from_pretrained(
39
40
41
42
43
            model_id,
            revision=revision,
            padding_side="left",
            truncation_side="left",
            trust_remote_code=trust_remote_code,
44
45
46
47
        )
        tokenizer.pad_token = tokenizer.eos_token

        config = AutoConfig.from_pretrained(
48
49
50
            model_id,
            revision=revision,
            trust_remote_code=trust_remote_code,
51
        )
52
        config.quantize = quantize
53
54

        torch.distributed.barrier(group=self.process_group)
55
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
56
57
58
        weights = Weights(
            filenames, device=device, dtype=dtype, process_group=self.process_group
        )
59
60
        if config.quantize == "gptq":
            weights._set_gptq_params(model_id)
61

62
        model = GPTNeoxForCausalLM(config, weights)
63
64
65

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

    def forward(
        self, input_ids, attention_mask, position_ids, past_key_values: Optional = None
    ):
78
79
80
81
82
83
84
        outputs = self.model.forward(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            use_cache=True,
        )
85

86
87
        logits = outputs.logits
        return logits, outputs.past_key_values