File size: 9,414 Bytes
030a0f8
 
 
 
9320186
030a0f8
9852b1b
 
e852933
 
030a0f8
 
 
 
 
 
 
 
 
e852933
030a0f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e94abdd
030a0f8
 
 
 
 
 
 
 
d0289f9
9852b1b
 
c2ef356
 
 
 
 
 
 
 
23b915b
 
 
c2ef356
6ba5cb1
a905c49
 
 
 
 
 
 
 
030a0f8
 
 
 
 
 
 
 
 
 
 
 
e94abdd
030a0f8
 
9852b1b
 
 
 
 
 
 
 
 
 
23b915b
a905c49
9852b1b
c2ef356
4e3c392
1e2066e
 
 
9852b1b
030a0f8
 
 
124c8d3
030a0f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2f0b3b
030a0f8
 
 
 
e2f0b3b
030a0f8
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
39
40
41
42
43
44
45
46
47
48
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
119
120
121
122
123
124
125
126
127
128
129
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
from typing import Optional, Union

import torch
import transformers
import streamlit as st

from plotly import graph_objects as go

from utils import get_lm


class Generator:
    def __init__(self, lm_model_name, device, entropy=None):

        self.device = device

        self.tokenizer = transformers.AutoTokenizer.from_pretrained(
            lm_model_name
        )
        self.lm = get_lm(lm_model_name).to(device)
        self.lm.eval()

        self.lm.config.pad_token_id = self.lm.config.eos_token_id
        self.tokenizer.add_special_tokens(
            {"pad_token": self.tokenizer.decode(self.lm.config.eos_token_id)}
        )
        self.caif_sampler = None
        self.ordinary_sampler = None
        self.entropy_based_stats = {
            "skips": 0,
            "avg_entropy": 0,
            "count": 0,
        }
        self.entropy = entropy

    def set_caif_sampler(self, sampler):
        self.caif_sampler = sampler

    def set_ordinary_sampler(self, sampler):
        self.ordinary_sampler = sampler

    def sample_sequences(
        self,
        num_samples: int,
        input_prompt: Optional[str],
        max_length: int,
        caif_period: int,
        caif_tokens_num: Union[int, None] = None,
        entropy: float = None,
        progress_bar=None,
        **sampler_kwargs
    ):
        self.entropy = entropy

        input_ids, past, ended_sequences = self.get_input_ids(
            input_prompt,
            num_samples,
        )
        text = st.empty()
        plot = st.empty()
        gen_history = []
        layout = go.Layout({
            "xaxis": {
                "title": "# Tokens"
            },
            "yaxis": {
                "title": "Desired Attribute"
            },
            "plot_bgcolor": '#FFFFFF',
            "template": "plotly_white",
            "hovermode": "x",

        })
        inp_len = len(input_ids[0])
        if self.caif_sampler is not None:
            current_decoded = self.tokenizer.decode(input_ids[0])
            probs = torch.exp(
                self.caif_sampler.get_classifier_log_probs(
                    current_decoded, target_cls_id=sampler_kwargs["target_cls_id"]
                )
            ).item()
            gen_history += [probs]
        for i in range(max_length):
            is_caif_step = (
                i % caif_period == 0 and self.caif_sampler is not None
            )
            input_ids, past, ended_sequences = self.generation_step(
                input_ids,
                past,
                ended_sequences,
                is_caif_step,
                caif_tokens_num=caif_tokens_num,
                **sampler_kwargs
            )
            progress_bar.progress((i+1)/max_length)
            if ended_sequences.all():
                break
            current_decoded = self.tokenizer.decode(input_ids[0])
            if self.caif_sampler is not None:
                probs = torch.exp(
                    self.caif_sampler.get_classifier_log_probs(
                        current_decoded, target_cls_id=sampler_kwargs["target_cls_id"]
                    )
                ).item()
                gen_history += [probs]
                scatter_data = go.Scatter({
                    "x": list(range(len(gen_history))),
                    "y": gen_history,
                    "hovertext": ["[PROMPT]"] + [self.tokenizer.decode(t) for t in input_ids[0][inp_len:]]
                })
                fig = go.Figure([scatter_data], layout=layout)
                plot.plotly_chart(fig, use_container_width=True)
                if i == 0:
                    with st.expander("What is it?"):
                        st.write("You can see how the probability of the desired attribute varies for every generation step.")
            text.text(current_decoded)

        return (
            [
                self.tokenizer.decode(sequence, skip_special_tokens=True)
                for sequence in input_ids
            ],
            input_ids,
        )

    def generation_step(
        self,
        input_ids,
        past,
        ended_sequences,
        is_caif_step: bool,
        caif_tokens_num=None,
        **sampler_kwargs
    ):
        prepared_inputs = self.lm.prepare_inputs_for_generation(
            input_ids, past, use_cache=True
        )
        outputs = self.lm(
            **prepared_inputs,
            output_attentions=False,
            output_hidden_states=False,
            return_dict=True
        )

        past = outputs.past_key_values
        if self.entropy is not None:
            normalized = torch.nn.functional.log_softmax(
                outputs.logits, dim=-1
            )
            p = torch.exp(normalized)
            output_probs = p
            output_information = -normalized
            output_entropy = (output_probs * output_information).sum(-1)[:, -1]
            batch_size = output_entropy.shape[0]
            caif_mask = torch.ge(output_entropy, self.entropy)
            ordinary_mask = ~caif_mask
            self.entropy_based_stats["skips"] += caif_mask.sum() / batch_size
            self.entropy_based_stats["count"] += 1
            self.entropy_based_stats["avg_entropy"] += (
                output_entropy.sum() / batch_size
            )
            flatten_entropy = output_entropy.view(-1).cpu().tolist()
            if "entropy" not in self.entropy_based_stats.keys():
                self.entropy_based_stats["entropy"] = flatten_entropy
            else:
                self.entropy_based_stats["entropy"] += flatten_entropy

            if caif_mask.sum() == 0:
                next_tokens_sampler = self.ordinary_sampler
                next_tokens = next_tokens_sampler(
                    input_ids,
                    outputs.logits,
                    caif_tokens_num=caif_tokens_num,
                    **sampler_kwargs
                )
                next_tokens = (
                    next_tokens * (1 - ended_sequences.long())
                    + self.lm.config.eos_token_id * ended_sequences.long()
                ).long()

            elif caif_mask.sum() == batch_size:
                next_tokens_sampler = self.caif_sampler
                next_tokens = next_tokens_sampler(
                    input_ids,
                    outputs.logits,
                    caif_tokens_num=caif_tokens_num,
                    **sampler_kwargs
                )
                next_tokens = (
                    next_tokens * (1 - ended_sequences.long())
                    + self.lm.config.eos_token_id * ended_sequences.long()
                ).long()

            else:
                next_tokens_caif = self.caif_sampler(
                    input_ids[caif_mask],
                    outputs.logits[caif_mask],
                    caif_tokens_num=caif_tokens_num,
                    **sampler_kwargs
                )
                next_tokens_ordinary = self.ordinary_sampler(
                    input_ids[ordinary_mask],
                    outputs.logits[ordinary_mask],
                    caif_tokens_num=caif_tokens_num,
                    **sampler_kwargs
                )
                next_tokens_caif = (
                    next_tokens_caif * (1 - ended_sequences[caif_mask].long())
                    + self.lm.config.eos_token_id
                    * ended_sequences[caif_mask].long()
                ).long()
                next_tokens_ordinary = (
                    next_tokens_ordinary
                    * (1 - ended_sequences[ordinary_mask].long())
                    + self.lm.config.eos_token_id
                    * ended_sequences[ordinary_mask].long()
                ).long()

                next_tokens = torch.ones(batch_size).long().to(self.device)
                next_tokens[caif_mask] = next_tokens_caif
                next_tokens[ordinary_mask] = next_tokens_ordinary
        else:
            if is_caif_step:
                next_tokens_sampler = self.caif_sampler
            else:
                next_tokens_sampler = self.ordinary_sampler

            next_tokens = next_tokens_sampler(
                input_ids,
                outputs.logits,
                caif_tokens_num=caif_tokens_num,
                **sampler_kwargs
            )

            next_tokens = (
                next_tokens * (1 - ended_sequences.long())
                + self.lm.config.eos_token_id * ended_sequences.long()
            ).long()

        input_ids = torch.cat(
            [input_ids, next_tokens[:, None].to(self.device)], dim=-1
        )

        ended_sequences += next_tokens == self.lm.config.eos_token_id

        return input_ids, past, ended_sequences

    def get_input_ids(self, input_prompt, num_samples):
        #input_ids = torch.tensor([[self.lm.config.bos_token_id]])
        if input_prompt is not None:
            input_prompt = self.tokenizer(
                input_prompt, return_tensors="pt"
            ).input_ids
            input_ids = input_prompt
        input_ids = input_ids.repeat(num_samples, 1).to(self.device)
        past = None
        ended_sequences = torch.zeros(
            input_ids.shape[0], device=self.device
        ).bool()

        return input_ids, past, ended_sequences

    @staticmethod
    def sample(unscaled_probs, values):
        samples = torch.multinomial(unscaled_probs, 1)
        return torch.take_along_dim(values, samples, dim=1)