File size: 12,753 Bytes
b599481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import json
import sys
from collections import defaultdict
from typing import Any, Dict, List, Tuple

import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from transformers import AutoTokenizer, BartConfig

sys.path.append("..")

from src.model.kbrd.kbrd_model import KBRDforConv, KBRDforRec
from src.model.kbrd.kg_kbrd import KGForKBRD
from src.model.utils import padded_tensor


class KBRD:
    def __init__(
        self,
        seed,
        kg_dataset,
        debug,
        hidden_size,
        entity_hidden_size,
        num_bases,
        rec_model,
        conv_model,
        context_max_length,
        tokenizer_path,
        encoder_layers,
        decoder_layers,
        text_hidden_size,
        attn_head,
        resp_max_length,
        entity_max_length,
    ):
        self.seed = seed
        if self.seed is not None:
            set_seed(self.seed)
        self.kg_dataset = kg_dataset
        # model detailed
        self.debug = debug
        self.hidden_size = hidden_size
        self.entity_hidden_size = entity_hidden_size
        self.num_bases = num_bases
        self.context_max_length = context_max_length
        self.entity_max_length = entity_max_length
        # model
        self.rec_model = rec_model
        self.conv_model = conv_model
        # conv
        self.tokenizer_path = tokenizer_path
        self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_path)
        self.encoder_layers = encoder_layers
        self.decoder_layers = decoder_layers
        self.text_hidden_size = text_hidden_size
        self.attn_head = attn_head
        self.resp_max_length = resp_max_length
        self.padding = "max_length"
        self.pad_to_multiple_of = 8

        self.kg_dataset_path = f"data/{self.kg_dataset}"
        with open(
            f"{self.kg_dataset_path}/entity2id.json", "r", encoding="utf-8"
        ) as f:
            self.entity2id = json.load(f)

        # Initialize the accelerator.
        self.accelerator = Accelerator(
            device_placement=False, mixed_precision="fp16"
        )
        self.device = self.accelerator.device

        self.kg = KGForKBRD(
            kg_dataset=self.kg_dataset, debug=self.debug
        ).get_kg_info()
        self.pad_id = self.kg["pad_id"]

        # rec model
        self.crs_rec_model = KBRDforRec(
            hidden_size=self.hidden_size,
            num_relations=self.kg["num_relations"],
            num_bases=self.num_bases,
            num_entities=self.kg["num_entities"],
        )
        if self.rec_model is not None:
            self.crs_rec_model.load(self.rec_model)
        self.crs_rec_model = self.crs_rec_model.to(self.device)
        self.crs_rec_model = self.accelerator.prepare(self.crs_rec_model)

        # conv model
        config = BartConfig.from_pretrained(
            self.conv_model,
            encoder_layers=self.encoder_layers,
            decoder_layers=self.decoder_layers,
            hidden_size=self.text_hidden_size,
            encoder_attention_heads=self.attn_head,
            decoder_attention_heads=self.attn_head,
            encoder_ffn_dim=self.text_hidden_size,
            decoder_ffn_dim=self.text_hidden_size,
            forced_bos_token_id=None,
            forced_eos_token_id=None,
        )

        self.crs_conv_model = KBRDforConv(
            config, user_hidden_size=self.entity_hidden_size
        ).to(self.device)
        if self.conv_model is not None:
            self.crs_conv_model = KBRDforConv.from_pretrained(
                self.conv_model, user_hidden_size=self.entity_hidden_size
            ).to(self.device)
        self.crs_conv_model = self.accelerator.prepare(self.crs_conv_model)

    def get_rec(self, conv_dict):
        data_dict = {
            "item": [
                self.entity2id[rec]
                for rec in conv_dict["rec"]
                if rec in self.entity2id
            ],
        }

        entity_ids = (
            [
                self.entity2id[ent]
                for ent in conv_dict["entity"][-self.entity_max_length :]
                if ent in self.entity2id
            ],
        )

        if "dialog_id" in conv_dict:
            data_dict["dialog_id"] = conv_dict["dialog_id"]
        if "turn_id" in conv_dict:
            data_dict["turn_id"] = conv_dict["turn_id"]
        if "template" in conv_dict:
            data_dict["template"] = conv_dict["template"]

        # kg
        edge_index, edge_type = torch.as_tensor(
            self.kg["edge_index"], device=self.device
        ), torch.as_tensor(self.kg["edge_type"], device=self.device)

        entity_ids = padded_tensor(
            entity_ids,
            pad_id=self.pad_id,
            pad_tail=True,
            max_length=self.entity_max_length,
            device=self.device,
            debug=self.debug,
        )

        data_dict["entity"] = {
            "entity_ids": entity_ids,
            "entity_mask": torch.ne(entity_ids, self.pad_id),
        }

        # infer
        self.crs_rec_model.eval()

        with torch.no_grad():
            data_dict["entity"]["edge_index"] = edge_index
            data_dict["entity"]["edge_type"] = edge_type
            outputs = self.crs_rec_model(
                **data_dict["entity"], reduction="mean"
            )

            logits = outputs["logit"][:, self.kg["item_ids"]]
            ranks = torch.topk(logits, k=50, dim=-1).indices.tolist()
            preds = [
                [self.kg["item_ids"][rank] for rank in rank_list]
                for rank_list in ranks
            ]
            labels = data_dict["item"]

        return preds, labels

    def get_conv(self, conv_dict):
        self.tokenizer.truncation_side = "left"
        context_list = conv_dict["context"]
        context = f"{self.tokenizer.sep_token}".join(context_list)
        context_ids = self.tokenizer.encode(
            context, truncation=True, max_length=self.context_max_length
        )
        context_batch = defaultdict(list)
        context_batch["input_ids"] = context_ids
        context_ids = self.tokenizer.pad(
            context_batch,
            max_length=self.context_max_length,
            padding=self.padding,
            pad_to_multiple_of=self.pad_to_multiple_of,
        )

        self.tokenizer.truncation_side = "right"
        resp = conv_dict["resp"]
        resp_batch = defaultdict(list)
        resp_ids = self.tokenizer.encode(
            resp, truncation=True, max_length=self.resp_max_length
        )
        resp_batch["input_ids"] = resp_ids
        resp_batch = self.tokenizer.pad(
            resp_batch,
            max_length=self.resp_max_length,
            padding=self.padding,
            pad_to_multiple_of=self.pad_to_multiple_of,
        )

        context_batch["labels"] = resp_batch["input_ids"]

        for k, v in context_batch.items():
            if not isinstance(v, torch.Tensor):
                context_batch[k] = torch.as_tensor(
                    v, device=self.device
                ).unsqueeze(0)

        entity_list = (
            [
                self.entity2id[ent]
                for ent in conv_dict["entity"][-self.entity_max_length :]
                if ent in self.entity2id
            ],
        )

        entity_ids = padded_tensor(
            entity_list,
            pad_id=self.pad_id,
            pad_tail=True,
            device=self.device,
            debug=self.debug,
            max_length=self.context_max_length,
        )

        entity = {
            "entity_ids": entity_ids,
            "entity_mask": torch.ne(entity_ids, self.pad_id),
        }

        data_dict = {"context": context_batch, "entity": entity}

        edge_index, edge_type = torch.as_tensor(
            self.kg["edge_index"], device=self.device
        ), torch.as_tensor(self.kg["edge_type"], device=self.device)

        node_embeds = self.crs_rec_model.get_node_embeds(edge_index, edge_type)
        user_embeds = self.crs_rec_model(
            **data_dict["entity"], node_embeds=node_embeds
        )["user_embeds"]

        gen_inputs = {
            **data_dict["context"],
            "decoder_user_embeds": user_embeds,
        }
        gen_inputs.pop("labels")

        gen_args = {
            "min_length": 0,
            "max_length": self.resp_max_length,
            "num_beams": 1,
            "no_repeat_ngram_size": 3,
            "encoder_no_repeat_ngram_size": 3,
        }
        gen_seqs = self.accelerator.unwrap_model(self.crs_conv_model).generate(
            **gen_inputs, **gen_args
        )
        gen_str = self.tokenizer.decode(gen_seqs[0], skip_special_tokens=True)
        return gen_inputs, gen_str

    def get_choice(self, gen_inputs, options, state, conv_dict=None):
        state = torch.as_tensor(state, device=self.device)
        outputs = self.accelerator.unwrap_model(self.crs_conv_model).generate(
            **gen_inputs,
            min_new_tokens=2,
            max_new_tokens=2,
            num_beams=1,
            return_dict_in_generate=True,
            output_scores=True,
        )
        option_token_ids = [
            self.tokenizer.encode(op, add_special_tokens=False)[0]
            for op in options
        ]
        option_scores = outputs.scores[-1][0][option_token_ids]
        option_scores += state
        option_with_max_score = options[torch.argmax(option_scores)]

        return option_with_max_score

    def get_response(
        self,
        conv_dict: Dict[str, Any],
        id2entity: Dict[int, str],
        options: Tuple[str, Dict[str, str]],
        state: List[float],
    ) -> Tuple[str, List[float]]:
        """Generates a response given a conversation context.

        The method is based on the logic of the ask mode (i.e., see
        `scripts/ask.py`). It consists of two steps: (1) choose to either
        recommend items or generate a response, and (2) execute the chosen
        step. Slightly deviates from the original implementation by not using
        templates.

        Args:
            conv_dict: Conversation context.
            id2entity: Mapping from entity id to entity name.
            options: Prompt with options and dictionary of options.
            state: State of the option choices.

        Returns:
            Generated response and updated state.
        """
        generated_inputs, generated_response = self.get_conv(conv_dict)
        options_letter = list(options[1].keys())

        # Get the choice between recommend and generate
        choice = self.get_choice(generated_inputs, options_letter, state)

        if choice == options_letter[-1]:
            # Generate a recommendation
            recommended_items, _ = self.get_rec(conv_dict)
            recommended_items_str = ""
            for i, item_id in enumerate(recommended_items[0][:3]):
                recommended_items_str += f"{i+1}: {id2entity[item_id]}  \n"
            response = (
                "I would recommend the following items:  \n"
                f"{recommended_items_str}"
            )
        else:
            # Original : Generate a response to ask for preferences. The
            # fallback is to use the generated response.
            # response = (
            #     options[1].get(choice, {}).get("template", generated_response)
            # )
            response = generated_response

        # Update the state. Hack: penalize the choice to reduce the
        # likelihood of selecting the same choice again
        state[options_letter.index(choice)] += -1e5

        return response, state


if __name__ == "__main__":
    # print(sys.path)
    kbrd = KBRD(
        seed=42,
        kg_dataset="redial",
        debug=False,
        hidden_size=128,
        num_bases=8,
        rec_model=f"/mnt/tangxinyu/crs/eval_model/redial_rec/best",
        conv_model="/mnt/tangxinyu/crs/eval_model/redial_conv/final/",
        encoder_layers=2,
        decoder_layers=2,
        attn_head=2,
        resp_max_length=128,
        text_hidden_size=300,
        entity_hidden_size=128,
        context_max_length=200,
        entity_max_length=32,
        tokenizer_path="../utils/tokenizer/bart-base",
    )
    # print(kbrd)
    context_dict = {
        "dialog_id": "20001",
        "turn_id": 1,
        "context": ["Hi I am looking for a movie like Super Troopers (2001)"],
        "entity": ["Super Troopers (2001)"],
        "rec": ["Police Academy (1984)"],
        "resp": "You should watch Police Academy (1984)",
        "template": [
            "Hi I am looking for a movie like <mask>",
            "You should watch <mask>",
        ],
    }
    preds, labels = kbrd.get_rec(context_dict)
    gen_seq = kbrd.get_conv(context_dict)