gpt2.py 3.81 KB
Newer Older
Jason Phang's avatar
gpt3  
Jason Phang committed
1
import torch
Xingjian Shi's avatar
Xingjian Shi committed
2
import transformers
3
from lm_eval.base import BaseLM
Jason Phang's avatar
gpt3  
Jason Phang committed
4

5
class HFLM(BaseLM):
Fabrizio Milo's avatar
Fabrizio Milo committed
6
7
8
9
10
    def __init__(
        self,
        device="cuda",
        pretrained="gpt2",
        revision="main",
Xingjian Shi's avatar
Xingjian Shi committed
11
        low_cpu_mem_usage=None,
Fabrizio Milo's avatar
Fabrizio Milo committed
12
13
14
15
        subfolder=None,
        tokenizer=None,
        batch_size=1,
    ):
Leo Gao's avatar
Leo Gao committed
16
        super().__init__()
17
18
19

        assert isinstance(device, str)
        assert isinstance(pretrained, str)
20
        assert isinstance(batch_size, (int,str))
21

Fabrizio Milo's avatar
Fabrizio Milo committed
22
        if device:
23
24
            if device not in ["cuda", "cpu"]:
                device = int(device)
researcher2's avatar
researcher2 committed
25
            self._device = torch.device(device)
26
            print(f"Using device '{device}'")
Leo Gao's avatar
Leo Gao committed
27
        else:
Fabrizio Milo's avatar
Fabrizio Milo committed
28
            print("Device not specified")
29
            print(f"Cuda Available? {torch.cuda.is_available()}")
Fabrizio Milo's avatar
Fabrizio Milo committed
30
31
32
33
34
            self._device = (
                torch.device("cuda")
                if torch.cuda.is_available()
                else torch.device("cpu")
            )
35

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

39
        self.gpt2 = transformers.AutoModelForCausalLM.from_pretrained(
Xingjian Shi's avatar
Xingjian Shi committed
40
            pretrained, revision=revision, low_cpu_mem_usage=low_cpu_mem_usage
41
        ).to(self.device)
Leo Gao's avatar
Leo Gao committed
42
        self.gpt2.eval()
Leo Gao's avatar
Leo Gao committed
43

44
        self.tokenizer = transformers.AutoTokenizer.from_pretrained(
Fabrizio Milo's avatar
Fabrizio Milo committed
45
            pretrained if tokenizer is None else tokenizer,
46
            revision=revision,
Fabrizio Milo's avatar
Fabrizio Milo committed
47
        )
48

Fabrizio Milo's avatar
Fabrizio Milo committed
49
50
51
52
53
54
55
56
57
        assert isinstance(
            self.tokenizer,
            (
                transformers.GPT2Tokenizer,
                transformers.GPT2TokenizerFast,
                transformers.T5Tokenizer,
                transformers.T5TokenizerFast,
            ),
        ), "this tokenizer has not been checked for compatibility yet!"
58

59
        self.vocab_size = self.tokenizer.vocab_size
60

Fabrizio Milo's avatar
Fabrizio Milo committed
61
62
63
64
65
66
67
68
69
        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
70

71
72
73
74
75
        # setup for automatic batch size detection
        if batch_size == 'auto': 
            self.batch_size_per_gpu = batch_size
        else:
            self.batch_size_per_gpu = int(batch_size) 
76
77


78
79
80
81
    @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
82

83
84
85
86
87
88
89
    @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
90

91
92
93
    @property
    def max_gen_toks(self):
        return 256
Leo Gao's avatar
Leo Gao committed
94

95
96
97
98
    @property
    def batch_size(self):
        # TODO: fix multi-gpu
        return self.batch_size_per_gpu  # * gpus
Leo Gao's avatar
Leo Gao committed
99

100
101
102
103
    @property
    def device(self):
        # TODO: fix multi-gpu
        return self._device
Leo Gao's avatar
Leo Gao committed
104

105
106
    def tok_encode(self, string: str):
        return self.tokenizer.encode(string, add_special_tokens=False)
Fabrizio Milo's avatar
Fabrizio Milo committed
107

108
109
110
    def tok_decode(self, tokens):
        return self.tokenizer.decode(tokens)

Leo Gao's avatar
Leo Gao committed
111
112
113
114
115
116
    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
117
        logits returned from the model
Leo Gao's avatar
Leo Gao committed
118
        """
119
        with torch.no_grad():
120
            return self.gpt2(inps)[0]
Fabrizio Milo's avatar
Fabrizio Milo committed
121

122
123
    def _model_generate(self, context, max_length, eos_token_id):
        return self.gpt2.generate(
Fabrizio Milo's avatar
Fabrizio Milo committed
124
            context, max_length=max_length, eos_token_id=eos_token_id, do_sample=False
125
126
127
        )


128
129
# for backwards compatibility
GPT2LM = HFLM