gptj.py 4.55 KB
Newer Older
Tian Yun's avatar
Tian Yun committed
1
2
3
4
5
6
7
8
9
10
import transformers
import torch
from lm_eval.base import BaseLM


class GPTJLM(BaseLM):
    def __init__(
        self,
        device="cuda",
        batch_size=1,
Tian Yun's avatar
Tian Yun committed
11
        parallelize=False,
Tian Yun's avatar
Tian Yun committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    ):
        super().__init__()

        assert isinstance(device, str)
        assert isinstance(batch_size, int)

        if device:
            self._device = torch.device(device)
        else:
            self._device = (
                torch.device("cuda")
                if torch.cuda.is_available()
                else torch.device("cpu")
            )

        pretrained = "EleutherAI/gpt-j-6B"
        self.gptj = transformers.AutoModelForCausalLM.from_pretrained(pretrained).to(self.device)
        self.gptj.eval()

        # pretrained tokenizer for neo is broken for now so just hard-coding this to gptj
        self.tokenizer = transformers.AutoTokenizer.from_pretrained(pretrained)
        self.vocab_size = self.tokenizer.vocab_size

        # multithreading and batching
        self.batch_size_per_gpu = batch_size  # todo: adaptive batch size

        # TODO: fix multi-gpu
Tian Yun's avatar
Tian Yun committed
39
40
41
42
43
        if parallelize:
            self.gptj.parallelize()
            self._device = torch.device('cuda:0')
        else:
            self.gptj.to(self._device)
Tian Yun's avatar
Tian Yun committed
44

jon-tow's avatar
jon-tow committed
45
46
47
48
    @property
    def eot_token(self):
        return self.tokenizer.eos_token

Tian Yun's avatar
Tian Yun committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
118
    @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.gptj.config.n_ctx
        except AttributeError:
            # gptneoconfig doesn't have n_ctx apparently
            return self.gptj.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

    def tok_encode(self, string: str):
        return self.tokenizer.encode(string, add_special_tokens=False)

    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
        logits returned from the model
        """
        with torch.no_grad():
            return self.gptj(inps)[0][:, :, :50257]

    def _get_stopping_criteria(self, stopping_criteria_ids):
        class MultitokenEOSCriteria(transformers.StoppingCriteria):
            def __init__(self, eos_seq_id: torch.LongTensor, tokenizer):
                self.eos_seq = tokenizer.decode(eos_seq_id)
                self.eos_seq_id = eos_seq_id
                self.eos_seq_len = len(eos_seq_id) + 1
                self.tokenizer = tokenizer

            def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
                last_token_id = input_ids[0, -self.eos_seq_len:]
                last_tokens = self.tokenizer.decode(last_token_id)
                is_stopped = self.eos_seq in last_tokens
                return is_stopped
        
        class EOSCriteria(transformers.StoppingCriteria):
            def __init__(self, eos_token_id: torch.LongTensor):
                self.eos_token_id = eos_token_id

            def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
                return input_ids[0,-1] == self.eos_token_id
         
        return transformers.StoppingCriteriaList([
            MultitokenEOSCriteria(stopping_criteria_ids, self.tokenizer),
            EOSCriteria(self.tokenizer.eos_token)
        ])

Tian Yun's avatar
Tian Yun committed
119
    def _model_generate(self, context, max_length, stopping_criteria_ids, num_fewshot):
Tian Yun's avatar
Tian Yun committed
120
        stopping_criteria = self._get_stopping_criteria(stopping_criteria_ids)
jon-tow's avatar
jon-tow committed
121
        max_length = max_length + context.size(1)
Tian Yun's avatar
Tian Yun committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        if num_fewshot == 0:
            generations = self.gptj.generate(
                context, 
                max_length=max_length, 
                eos_token_id=self.eot_token_id,
                do_sample=False,
            )
        else:
            generations = self.gptj.generate(
                context, 
                max_length=max_length, 
                stopping_criteria=stopping_criteria,
                do_sample=False,
            )

        # Remove the context from the generations
        return generations[0, context.shape[1] :]