gpt2.py 4.53 KB
Newer Older
Jason Phang's avatar
gpt3  
Jason Phang committed
1
import torch
Xingjian Shi's avatar
Xingjian Shi committed
2
import transformers
cardy20's avatar
cardy20 committed
3
from typing import Optional, Union
4
from lm_eval.base import BaseLM
Jason Phang's avatar
gpt3  
Jason Phang committed
5

6

cardy20's avatar
cardy20 committed
7
8
9
10
11
12
13
14
15
16
17
18
def _get_dtype(
    dtype: Union[str, torch.dtype]
) -> torch.dtype:
    """Converts `dtype` from `str` to torch.dtype when possible. Does not use an instantiated HF AutoConfig"""
    if isinstance(dtype, str) and dtype != "auto":
        # Convert `str` args torch dtype: `float16` -> `torch.float16`
        _torch_dtype = getattr(torch, dtype)
    else:
        _torch_dtype = dtype
    return _torch_dtype


19
class HFLM(BaseLM):
Fabrizio Milo's avatar
Fabrizio Milo committed
20
21
22
23
24
    def __init__(
        self,
        device="cuda",
        pretrained="gpt2",
        revision="main",
Xingjian Shi's avatar
Xingjian Shi committed
25
        low_cpu_mem_usage=None,
Fabrizio Milo's avatar
Fabrizio Milo committed
26
27
28
        subfolder=None,
        tokenizer=None,
        batch_size=1,
29
30
        load_in_8bit: Optional[bool] = False,
        trust_remote_code: Optional[bool] = False,
cardy20's avatar
cardy20 committed
31
        dtype: Optional[Union[str, torch.dtype]]="auto",
Fabrizio Milo's avatar
Fabrizio Milo committed
32
    ):
33
34
35
36
        super().__init__()

        assert isinstance(device, str)
        assert isinstance(pretrained, str)
37
        assert isinstance(batch_size, (int, str))
38

39
40
41
        device_list = set(
            ["cuda", "cpu"] + [f"cuda:{i}" for i in range(torch.cuda.device_count())]
        )
42
        if device and device in device_list:
43
            self._device = torch.device(device)
44
            print(f"Using device '{device}'")
45
        else:
Fabrizio Milo's avatar
Fabrizio Milo committed
46
            print("Device not specified")
47
            print(f"Cuda Available? {torch.cuda.is_available()}")
Fabrizio Milo's avatar
Fabrizio Milo committed
48
49
50
51
52
            self._device = (
                torch.device("cuda")
                if torch.cuda.is_available()
                else torch.device("cpu")
            )
53
54

        # TODO: update this to be less of a hack once subfolder is fixed in HF
55
56
        revision = revision + ("/" + subfolder if subfolder is not None else "")

57
        self.gpt2 = transformers.AutoModelForCausalLM.from_pretrained(
58
59
60
61
            pretrained,
            load_in_8bit=load_in_8bit,
            low_cpu_mem_usage=low_cpu_mem_usage,
            revision=revision,
cardy20's avatar
cardy20 committed
62
            torch_dtype=_get_dtype(dtype),
63
            trust_remote_code=trust_remote_code,
64
        ).to(self.device)
65
66
        self.gpt2.eval()

67
        self.tokenizer = transformers.AutoTokenizer.from_pretrained(
kabbi159's avatar
kabbi159 committed
68
            pretrained if tokenizer is None else tokenizer,
69
            revision=revision,
70
            trust_remote_code=trust_remote_code,
Fabrizio Milo's avatar
Fabrizio Milo committed
71
        )
72

73
        self.vocab_size = self.tokenizer.vocab_size
74

Fabrizio Milo's avatar
Fabrizio Milo committed
75
76
77
78
79
80
81
82
83
        if isinstance(
            self.tokenizer, (transformers.GPT2Tokenizer, transformers.GPT2TokenizerFast)
        ):
            assert self.tokenizer.encode("hello\n\nhello") == [
                31373,
                198,
                198,
                31373,
            ], self.tokenizer.encode("hello\n\nhello")
Leo Gao's avatar
Leo Gao committed
84

85
        # setup for automatic batch size detection
86
        if batch_size == "auto":
87
88
            self.batch_size_per_gpu = batch_size
        else:
89
            self.batch_size_per_gpu = int(batch_size)
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

    @property
    def eot_token_id(self):
        # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
        return self.tokenizer.eos_token_id

    @property
    def max_length(self):
        try:
            return self.gpt2.config.n_ctx
        except AttributeError:
            # gptneoconfig doesn't have n_ctx apparently
            return self.gpt2.config.max_position_embeddings

    @property
    def max_gen_toks(self):
        return 256

    @property
    def batch_size(self):
        # TODO: fix multi-gpu
        return self.batch_size_per_gpu  # * gpus

    @property
    def device(self):
        # TODO: fix multi-gpu
        return self._device

118
119
    def tok_encode(self, string: str):
        return self.tokenizer.encode(string, add_special_tokens=False)
soqeue1's avatar
soqeue1 committed
120

121
122
123
124
125
126
127
128
129
    def tok_decode(self, tokens):
        return self.tokenizer.decode(tokens)

    def _model_call(self, inps):
        """
        inps: a torch tensor of shape [batch, sequence]
        the size of sequence may vary from call to call

        returns: a torch tensor of shape [batch, sequence, vocab] with the
130
        logits returned from the model
131
132
        """
        with torch.no_grad():
Jiwung Hyun's avatar
Jiwung Hyun committed
133
            return self.gpt2(inps)[0]
soqeue1's avatar
soqeue1 committed
134

135
    def _model_generate(self, context, max_length, eos_token_id):
136
        generation_kwargs = {"do_sample": False, "max_length": max_length}
137
138
        if eos_token_id is not None:
            generation_kwargs['eos_token_id'] = eos_token_id
Nikhil Pinnaparaju's avatar
Nikhil Pinnaparaju committed
139
            generation_kwargs['pad_token_id'] = eos_token_id # setting eos_token_id as pad token
140
        return self.gpt2.generate(context, **generation_kwargs)
141
142


143
# for backwards compatibility
cardy20's avatar
cardy20 committed
144
GPT2LM = HFLM