gpt_neox.py 2.38 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
        trust_remote_code: bool = False,
28
    ):
29
        self.process_group, rank, world_size = initialize_torch_distributed()
30
        if torch.cuda.is_available():
31
            device = torch.device(f"cuda:{rank}")
32
            dtype = torch.float16
33
34
35
36
37
        else:
            device = torch.device("cpu")
            dtype = torch.float32

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

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

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

59
        model = GPTNeoxForCausalLM(config, weights)
60
61
62

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

    def forward(
        self, input_ids, attention_mask, position_ids, past_key_values: Optional = None
    ):
75
76
77
78
79
80
81
        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,
        )
82

83
84
        logits = outputs.logits
        return logits, outputs.past_key_values