test_pipelines_conversational.py 16 KB
Newer Older
Sylvain Gugger's avatar
Sylvain Gugger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
16
import unittest

17
from transformers import (
18
19
20
21
    MODEL_FOR_CAUSAL_LM_MAPPING,
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
22
    AutoModelForCausalLM,
23
24
    AutoModelForSeq2SeqLM,
    AutoTokenizer,
25
26
    BlenderbotSmallForConditionalGeneration,
    BlenderbotSmallTokenizer,
27
28
29
30
    Conversation,
    ConversationalPipeline,
    pipeline,
)
31
from transformers.testing_utils import is_pipeline_test, require_torch, slow, torch_device
32

33
from .test_pipelines_common import ANY, PipelineTestCaseMeta
34
35
36
37
38


DEFAULT_DEVICE_NUM = -1 if torch_device == "cpu" else 0


39
@is_pipeline_test
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
class ConversationalPipelineTests(unittest.TestCase, metaclass=PipelineTestCaseMeta):
    model_mapping = dict(
        list(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items())
        if MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
        else [] + list(MODEL_FOR_CAUSAL_LM_MAPPING.items())
        if MODEL_FOR_CAUSAL_LM_MAPPING
        else []
    )
    tf_model_mapping = dict(
        list(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items())
        if TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
        else [] + list(TF_MODEL_FOR_CAUSAL_LM_MAPPING.items())
        if TF_MODEL_FOR_CAUSAL_LM_MAPPING
        else []
    )

    def run_pipeline_test(self, model, tokenizer, feature_extractor):
        conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer)
        # Simple
        outputs = conversation_agent(Conversation("Hi there!"))
        self.assertEqual(outputs, Conversation(past_user_inputs=["Hi there!"], generated_responses=[ANY(str)]))

        # Single list
        outputs = conversation_agent([Conversation("Hi there!")])
        self.assertEqual(outputs, Conversation(past_user_inputs=["Hi there!"], generated_responses=[ANY(str)]))

        # Batch
67
68
69
70
71
        conversation_1 = Conversation("Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)

72
73
        outputs = conversation_agent([conversation_1, conversation_2])
        self.assertEqual(outputs, [conversation_1, conversation_2])
74
        self.assertEqual(
75
            outputs,
76
77
78
            [
                Conversation(
                    past_user_inputs=["Going to the movies tonight - any suggestions?"],
79
                    generated_responses=[ANY(str)],
80
                ),
81
                Conversation(past_user_inputs=["What's the last book you have read?"], generated_responses=[ANY(str)]),
82
83
84
85
86
            ],
        )

        # One conversation with history
        conversation_2.add_user_input("Why do you recommend it?")
87
88
        outputs = conversation_agent(conversation_2)
        self.assertEqual(outputs, conversation_2)
89
        self.assertEqual(
90
            outputs,
91
92
            Conversation(
                past_user_inputs=["What's the last book you have read?", "Why do you recommend it?"],
93
                generated_responses=[ANY(str), ANY(str)],
94
95
            ),
        )
96
97
98
99
        with self.assertRaises(ValueError):
            conversation_agent("Hi there!")
        with self.assertRaises(ValueError):
            conversation_agent(Conversation())
100
        # Conversation have been consumed and are not valid anymore
101
        # Inactive conversations passed to the pipeline raise a ValueError
102
103
        with self.assertRaises(ValueError):
            conversation_agent(conversation_2)
104
105
106
107
108

    @require_torch
    @slow
    def test_integration_torch_conversation(self):
        # When
109
        conversation_agent = pipeline(task="conversational", device=DEFAULT_DEVICE_NUM)
110
111
112
113
114
115
        conversation_1 = Conversation("Going to the movies tonight - any suggestions?")
        conversation_2 = Conversation("What's the last book you have read?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
116
        result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000)
117
118
119
120
121
122
123
124
125
126
127
128
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0], "Going to the movies tonight - any suggestions?")
        self.assertEqual(result[0].generated_responses[0], "The Big Lebowski")
        self.assertEqual(result[1].past_user_inputs[0], "What's the last book you have read?")
        self.assertEqual(result[1].generated_responses[0], "The Last Question")
        # When
        conversation_2.add_user_input("Why do you recommend it?")
129
        result = conversation_agent(conversation_2, do_sample=False, max_length=1000)
130
131
132
133
134
135
136
137
138
139
140
        # Then
        self.assertEqual(result, conversation_2)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Why do you recommend it?")
        self.assertEqual(result.generated_responses[1], "It's a good book.")

    @require_torch
    @slow
    def test_integration_torch_conversation_truncated_history(self):
        # When
141
        conversation_agent = pipeline(task="conversational", min_length_for_response=24, device=DEFAULT_DEVICE_NUM)
142
143
144
145
        conversation_1 = Conversation("Going to the movies tonight - any suggestions?")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        # When
146
        result = conversation_agent(conversation_1, do_sample=False, max_length=36)
147
148
149
150
151
152
153
154
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 1)
        self.assertEqual(len(result.generated_responses), 1)
        self.assertEqual(result.past_user_inputs[0], "Going to the movies tonight - any suggestions?")
        self.assertEqual(result.generated_responses[0], "The Big Lebowski")
        # When
        conversation_1.add_user_input("Is it an action movie?")
155
        result = conversation_agent(conversation_1, do_sample=False, max_length=36)
156
157
158
159
160
161
        # Then
        self.assertEqual(result, conversation_1)
        self.assertEqual(len(result.past_user_inputs), 2)
        self.assertEqual(len(result.generated_responses), 2)
        self.assertEqual(result.past_user_inputs[1], "Is it an action movie?")
        self.assertEqual(result.generated_responses[1], "It's a comedy.")
162

163
164
165
166
167
    @require_torch
    @slow
    def test_integration_torch_conversation_dialogpt_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
        model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
168
        conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer)
169
170

        conversation_1 = Conversation("hello")
171
        inputs = conversation_agent._parse_and_tokenize([conversation_1])
172
173
174
        self.assertEqual(inputs["input_ids"].tolist(), [[31373, 50256]])

        conversation_2 = Conversation("how are you ?", past_user_inputs=["hello"], generated_responses=["Hi there!"])
175
        inputs = conversation_agent._parse_and_tokenize([conversation_2])
176
177
178
179
        self.assertEqual(
            inputs["input_ids"].tolist(), [[31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633, 50256]]
        )

180
        inputs = conversation_agent._parse_and_tokenize([conversation_1, conversation_2])
181
182
183
184
185
186
187
188
189
190
191
192
193
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                [31373, 50256, 50256, 50256, 50256, 50256, 50256, 50256, 50256, 50256, 50256],
                [31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633, 50256],
            ],
        )

    @require_torch
    @slow
    def test_integration_torch_conversation_blenderbot_400M_input_ids(self):
        tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-400M-distill")
194
        conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer)
195
196
197

        # test1
        conversation_1 = Conversation("hello")
198
        inputs = conversation_agent._parse_and_tokenize([conversation_1])
199
200
201
202
203
204
205
206
207
208
        self.assertEqual(inputs["input_ids"].tolist(), [[1710, 86, 2]])

        # test2
        conversation_1 = Conversation(
            "I like lasagne.",
            past_user_inputs=["hello"],
            generated_responses=[
                " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie."
            ],
        )
209
        inputs = conversation_agent._parse_and_tokenize([conversation_1])
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
        self.assertEqual(
            inputs["input_ids"].tolist(),
            [
                # This should be compared with the same conversation on ParlAI `safe_interactive` demo.
                [
                    1710,  # hello
                    86,
                    228,  # Double space
                    228,
                    946,
                    304,
                    398,
                    6881,
                    558,
                    964,
                    38,
                    452,
                    315,
                    265,
                    6252,
                    452,
                    322,
                    968,
                    6884,
                    3146,
                    278,
                    306,
                    265,
                    617,
                    87,
                    388,
                    75,
                    341,
                    286,
                    521,
                    21,
                    228,  # Double space
                    228,
                    281,  # I like lasagne.
                    398,
                    6881,
                    558,
                    964,
                    21,
                    2,  # EOS
                ]
            ],
        )

259
260
261
262
263
    @require_torch
    @slow
    def test_integration_torch_conversation_blenderbot_400M(self):
        tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
        model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-400M-distill")
264
        conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer)
265
266

        conversation_1 = Conversation("hello")
267
        result = conversation_agent(
268
269
270
271
272
273
274
275
276
277
            conversation_1,
        )
        self.assertEqual(
            result.generated_responses[0],
            # ParlAI implementation output, we have a different one, but it's our
            # second best, you can check by using num_return_sequences=10
            # " Hello! How are you? I'm just getting ready to go to work, how about you?",
            " Hello! How are you doing today? I just got back from a walk with my dog.",
        )

278
        conversation_1 = Conversation("Lasagne   hello")
279
        result = conversation_agent(conversation_1, encoder_no_repeat_ngram_size=3)
280
281
        self.assertEqual(
            result.generated_responses[0],
282
            " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie.",
283
284
285
286
287
        )

        conversation_1 = Conversation(
            "Lasagne   hello   Lasagne is my favorite Italian dish. Do you like lasagne?   I like lasagne."
        )
288
        result = conversation_agent(
289
290
291
292
293
            conversation_1,
            encoder_no_repeat_ngram_size=3,
        )
        self.assertEqual(
            result.generated_responses[0],
294
            " Me too. I like how it can be topped with vegetables, meats, and condiments.",
295
296
        )

297
298
299
300
    @require_torch
    @slow
    def test_integration_torch_conversation_encoder_decoder(self):
        # When
Lysandre Debut's avatar
Lysandre Debut committed
301
302
        tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
        model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot_small-90M")
303
        conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer, device=DEFAULT_DEVICE_NUM)
304
305
306
307
308
309
310

        conversation_1 = Conversation("My name is Sarah and I live in London")
        conversation_2 = Conversation("Going to the movies tonight, What movie would you recommend? ")
        # Then
        self.assertEqual(len(conversation_1.past_user_inputs), 0)
        self.assertEqual(len(conversation_2.past_user_inputs), 0)
        # When
311
        result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000)
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 1)
        self.assertEqual(len(result[1].past_user_inputs), 1)
        self.assertEqual(len(result[0].generated_responses), 1)
        self.assertEqual(len(result[1].generated_responses), 1)
        self.assertEqual(result[0].past_user_inputs[0], "My name is Sarah and I live in London")
        self.assertEqual(
            result[0].generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result[1].past_user_inputs[0], "Going to the movies tonight, What movie would you recommend? "
        )
        self.assertEqual(
            result[1].generated_responses[0], "i don't know... i'm not really sure. what movie are you going to see?"
        )
        # When
        conversation_1.add_user_input("Not yet, what about you?")
        conversation_2.add_user_input("What's your name?")
332
        result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000)
333
334
335
336
337
338
339
340
341
342
        # Then
        self.assertEqual(result, [conversation_1, conversation_2])
        self.assertEqual(len(result[0].past_user_inputs), 2)
        self.assertEqual(len(result[1].past_user_inputs), 2)
        self.assertEqual(len(result[0].generated_responses), 2)
        self.assertEqual(len(result[1].generated_responses), 2)
        self.assertEqual(result[0].past_user_inputs[1], "Not yet, what about you?")
        self.assertEqual(result[0].generated_responses[1], "i don't have any plans yet. i'm not sure what to do yet.")
        self.assertEqual(result[1].past_user_inputs[1], "What's your name?")
        self.assertEqual(result[1].generated_responses[1], "i don't have a name, but i'm going to see a horror movie.")
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

    @require_torch
    @slow
    def test_from_pipeline_conversation(self):
        model_id = "facebook/blenderbot_small-90M"

        # from model id
        conversation_agent_from_model_id = pipeline("conversational", model=model_id, tokenizer=model_id)

        # from model object
        model = BlenderbotSmallForConditionalGeneration.from_pretrained(model_id)
        tokenizer = BlenderbotSmallTokenizer.from_pretrained(model_id)
        conversation_agent_from_model = pipeline("conversational", model=model, tokenizer=tokenizer)

        conversation = Conversation("My name is Sarah and I live in London")
        conversation_copy = Conversation("My name is Sarah and I live in London")

        result_model_id = conversation_agent_from_model_id([conversation])
        result_model = conversation_agent_from_model([conversation_copy])

        # check for equality
        self.assertEqual(
            result_model_id.generated_responses[0],
            "hi sarah, i live in london as well. do you have any plans for the weekend?",
        )
        self.assertEqual(
            result_model_id.generated_responses[0],
            result_model.generated_responses[0],
        )