t0.py 6.75 KB
Newer Older
Tian Yun's avatar
Tian Yun committed
1
2
3
4
import transformers
import torch
import torch.nn as nn
import torch.nn.functional as F
Tian Yun's avatar
Tian Yun committed
5
from lm_eval.base import BaseLM
Tian Yun's avatar
Tian Yun committed
6
7
8
9
10
from lm_eval import utils
from tqdm import tqdm
import numpy as np
import math

Tian Yun's avatar
Tian Yun committed
11
12
13
14
15
class T0LM(BaseLM):
    # MAX_GEN_TOKS = 256
    # MAX_INP_LENGTH = 512
    # VOCAB_SIZE = 32100
    # EOT_TOKEN_ID = 1
Tian Yun's avatar
Tian Yun committed
16
17
18
19

    def __init__(self, device='cuda', parallelize=False, pretrained='t0', batch_size=1):
        super().__init__()
        if device:
Tian Yun's avatar
Tian Yun committed
20
            self._device = torch.device(device)
Tian Yun's avatar
Tian Yun committed
21
        else:
Tian Yun's avatar
Tian Yun committed
22
23
            self._device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

Tian Yun's avatar
Tian Yun committed
24
25
26
27
28
        self.t0 = transformers.AutoModelForSeq2SeqLM.from_pretrained(pretrained)
        self.t0.eval()

        if parallelize == "True":
            self.t0.parallelize()
Tian Yun's avatar
Tian Yun committed
29
            self._device = torch.device('cuda:0')
Tian Yun's avatar
Tian Yun committed
30
        else:
Tian Yun's avatar
Tian Yun committed
31
            self.t0.to(self._device)
Tian Yun's avatar
Tian Yun committed
32
33

        self.tokenizer = transformers.AutoTokenizer.from_pretrained(pretrained)
Tian Yun's avatar
Tian Yun committed
34
        # self.max_length = self.MAX_INP_LENGTH
Tian Yun's avatar
Tian Yun committed
35
36
37
38
39
40
41
42
43

        self.batch_size = int(batch_size)

    @classmethod
    def create_from_arg_string(cls, arg_string, additional_config={}):
        args = utils.simple_parse_args_string(arg_string)
        args2 = {k: v for k, v in additional_config.items() if v is not None}
        return cls(**args, **args2)

Tian Yun's avatar
Tian Yun committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    @property
    def eot_token(self):
        return self.tokenizer.eos_token

    @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):
        return self.tokenizer.model_max_length

    @property
    def max_gen_toks(self):
Tian Yun's avatar
Tian Yun committed
59
        return 256
Tian Yun's avatar
Tian Yun committed
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

    @property
    def batch_size(self):
        # TODO: fix multi-gpu
        return self._batch_size  # * 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, inputs_tok, targets_tok):
        """
        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.t0(
                **inputs_tok,
                labels=targets_tok["input_ids"]
            )

Tian Yun's avatar
Tian Yun committed
91
92
93
94
95
96
    def loglikelihood(self, requests):
        res = []
        for chunk in tqdm(utils.chunks(requests, self.batch_size), total=math.ceil(len(requests)/self.batch_size)):

            inputs, targets = zip(*chunk)

Tian Yun's avatar
Tian Yun committed
97
98
99
100
101
102
103
104
            # Fill in empty encoder inputs with eos_token
            inputs = (
                f"{self.eot_token}" 
                if len(input_) == 0
                else input_
                for input_ in inputs
            )

Tian Yun's avatar
Tian Yun committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
            inputs_tok = self.tokenizer(
                list(inputs),
                max_length=self.max_length,
                padding=True,
                # truncation=True,
                add_special_tokens=False,
                return_tensors="pt"
                ).to(self.device)

            for key in inputs_tok:
                inputs_tok[key] = inputs_tok[key][:, -(self.max_length - 1) :]

            targets_tok = self.tokenizer(
                list(targets),
Tian Yun's avatar
Tian Yun committed
119
                max_length=self.max_gen_toks,
Tian Yun's avatar
Tian Yun committed
120
121
122
123
124
125
126
127
128
                padding=True,
                # truncation=True,
                add_special_tokens=False,
                return_tensors="pt"
                ).to(self.device)

            for key in targets_tok:
                targets_tok[key] = targets_tok[key][:, -(self.max_length - 1) :]

Tian Yun's avatar
Tian Yun committed
129
            outputs = self._model_call(inputs_tok, targets_tok)
Tian Yun's avatar
Tian Yun committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

            log_softmaxes = F.log_softmax(outputs.logits, dim=-1)
            
            output_iterator = zip(
                chunk,
                log_softmaxes,
                targets_tok["input_ids"],
                targets_tok["attention_mask"],
            )
            for cache_key, log_softmax, target_tok, target_mask in output_iterator:
                length = target_mask.sum()
                log_softmax = log_softmax[:length]
                target_tok = target_tok[:length]
                greedy_tokens = log_softmax.argmax(dim=-1)
                max_equal = (greedy_tokens == target_tok).all()
                target_logits = torch.gather(
                    log_softmax, 1, target_tok.unsqueeze(-1)
                ).squeeze(-1)
                answer = (float(target_logits.sum()), bool(max_equal))
            
                if cache_key is not None:
                    self.cache_hook.add_partial("loglikelihood", cache_key, answer)

                res.append(answer)

        return res

    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
183
    def _model_generate(self, context, max_length, stopping_criteria_ids, num_fewshot):
Tian Yun's avatar
Tian Yun committed
184
        stopping_criteria = self._get_stopping_criteria(stopping_criteria_ids)
Tian Yun's avatar
Tian Yun committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        
        if num_fewshot == 0:
            generations = self.t0.generate(
                context, 
                max_length=max_length, 
                eos_token_id=self.eot_token_id,
                do_sample=False,
            )
        else:
            generations = self.t0.generate(
                context, 
                max_length=max_length, 
                stopping_criteria=stopping_criteria,
                do_sample=False,
            )
        return generations[0]