File size: 15,761 Bytes
a01ef8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Intel Corporation
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
#

import os
import pytest
import shutil
import tempfile

from tlt.utils.file_utils import validate_model_name, download_and_extract_zip_file
from tlt.datasets import dataset_factory
from tlt.models import model_factory


@pytest.mark.integration
@pytest.mark.tensorflow
@pytest.mark.parametrize('model_name,dataset_name,extra_layers,correct_num_layers,model_hub',
                         [['google/bert_uncased_L-2_H-128_A-2', 'ag_news_subset', None, 5, 'huggingface']])
def test_tf_multi_text_classification(model_name, dataset_name, extra_layers, correct_num_layers, model_hub):
    """
    Tests basic transfer learning functionality for TensorFlow multi text classification using TF Datasets
    """
    framework = 'tensorflow'
    output_dir = tempfile.mkdtemp()
    os.environ["TENSORFLOW_HOME"] = output_dir

    try:
        # Get the dataset
        dataset = dataset_factory.get_dataset(output_dir, 'text_classification', framework, dataset_name,
                                              'tf_datasets', split=["train[:8%]"], shuffle_files=False)

        # Get the model
        model = model_factory.get_model(model_name, framework)

        # Preprocess the dataset
        batch_size = 32
        dataset.preprocess(batch_size)
        dataset.shuffle_split(seed=10)

        # This model does not support evaluate/predict before training
        with pytest.raises(ValueError) as e:
            model.evaluate(dataset)
        assert "model must be trained" in str(e)
        with pytest.raises(ValueError) as e:
            model.predict(dataset)
        assert "model must be trained" in str(e)

        # Train
        history = model.train(dataset, output_dir=output_dir, epochs=1,
                              shuffle_files=False, do_eval=False,
                              extra_layers=extra_layers)
        assert history is not None
        assert len(model._model.layers) == correct_num_layers

        # Verify that checkpoints were generated
        cleaned_name = validate_model_name(model_name)
        checkpoint_dir = os.path.join(output_dir, "{}_checkpoints".format(cleaned_name))
        assert os.path.isdir(checkpoint_dir)
        assert len(os.listdir(checkpoint_dir))

        # Evaluate
        trained_metrics = model.evaluate(dataset)
        assert len(trained_metrics) == 2  # expect to get loss and accuracy metrics

        # Predict with a batch
        input, labels = dataset.get_batch()
        predictions = model.predict(input)
        assert len(predictions) == batch_size

        text1 = ('Oil and Economy Cloud Stocks Outlook (Reuters) Reuters - '
                 'Soaring crude prices plus worries about the economy and the'
                 'outlook for earnings are expected to hang over the stock market'
                 'next week during the depth of the summer doldrums')
        text2 = ('Wall St. Bears Claw Back Into the Black (Reuters) Reuters -'
                 'Short-sellers, Wall Streets dwindlingband of ultra-cynics,'
                 'are seeing green again.')
        text3 = ('Expansion slows in Japan Economic growth in Japan slows down'
                 'as the country experiences a drop in domestic and corporate spending.'
                 'outlook for earnings are expected to hang over the stock market'
                 'next week during the depth of the summer doldrums')
        # Predict with raw text input
        raw_text_input = [text1, text2, text3]
        predictions = model.predict(raw_text_input)
        assert len(predictions) == len(raw_text_input)

        # export the saved model
        saved_model_dir = model.export(output_dir)
        assert os.path.isdir(saved_model_dir)
        assert os.path.isfile(os.path.join(saved_model_dir, "saved_model.pb"))

        # Reload the saved model
        reload_model = model_factory.load_model(model_name, saved_model_dir, framework, 'text_classification',
                                                model_hub)

        # Evaluate
        reload_metrics = reload_model.evaluate(dataset)
        assert reload_metrics == trained_metrics

        # Predict with the raw text input
        reload_predictions = reload_model.predict(raw_text_input)
        assert (reload_predictions == predictions).all()

        # Retrain from checkpoints and verify that accuracy metric is the expected type
        retrain_model = model_factory.load_model(model_name, saved_model_dir, framework, 'text_classification',
                                                 model_hub)
        retrain_model.train(dataset, output_dir=output_dir, epochs=1, initial_checkpoints=checkpoint_dir,
                            shuffle_files=False, do_eval=False)

        retrain_metrics = retrain_model.evaluate(dataset)
        accuracy_index = next(id for id, k in enumerate(model._model.metrics_names) if 'acc' in k)
        # BERT model results are not deterministic, so the commented assertion doesn't reliably pass
        assert isinstance(retrain_metrics[accuracy_index], float)

    finally:
        # Delete the temp output directory
        if os.path.exists(output_dir) and os.path.isdir(output_dir):
            shutil.rmtree(output_dir)


@pytest.mark.integration
@pytest.mark.tensorflow
@pytest.mark.parametrize('model_name,dataset_name,extra_layers,correct_num_layers,model_hub',
                         [['google/bert_uncased_L-2_H-128_A-2', 'imdb_reviews', None, 5, 'huggingface'],
                          ['google/bert_uncased_L-2_H-256_A-4', 'glue/sst2', None, 5, 'huggingface'],
                          ['google/bert_uncased_L-2_H-128_A-2', 'imdb_reviews', [512, 128], 7, 'huggingface']])
def test_tf_binary_text_classification(model_name, dataset_name, extra_layers, correct_num_layers, model_hub):
    """
    Tests basic transfer learning functionality for TensorFlow binary text classification using TF Datasets
    """
    framework = 'tensorflow'
    output_dir = tempfile.mkdtemp()

    try:
        # Get the dataset
        dataset = dataset_factory.get_dataset('/tmp/data', 'text_classification', framework, dataset_name,
                                              'tf_datasets', split=["train[:8%]"], shuffle_files=False)

        # Get the model
        model = model_factory.get_model(model_name, framework)

        # Preprocess the dataset
        batch_size = 32
        dataset.preprocess(batch_size)
        dataset.shuffle_split(seed=10)

        # This model does not support evaluate/predict before training
        with pytest.raises(ValueError) as e:
            model.evaluate(dataset)
        assert "model must be trained" in str(e)
        with pytest.raises(ValueError) as e:
            model.predict(dataset)
        assert "model must be trained" in str(e)

        # Train
        history = model.train(dataset, output_dir=output_dir, epochs=1,
                              shuffle_files=False, do_eval=False,
                              extra_layers=extra_layers)
        assert history is not None
        assert len(model._model.layers) == correct_num_layers

        # Verify that checkpoints were generated
        cleaned_name = validate_model_name(model_name)
        checkpoint_dir = os.path.join(output_dir, "{}_checkpoints".format(cleaned_name))
        assert os.path.isdir(checkpoint_dir)
        assert len(os.listdir(checkpoint_dir))

        # Evaluate
        trained_metrics = model.evaluate(dataset)
        assert len(trained_metrics) == 2  # expect to get loss and accuracy metrics

        # Predict with a batch
        input, labels = dataset.get_batch()
        predictions = model.predict(input)
        assert len(predictions) == batch_size

        # Predict with raw text input
        raw_text_input = ["awesome", "fun", "boring"]
        predictions = model.predict(raw_text_input)
        assert len(predictions) == len(raw_text_input)

        # export the saved model
        saved_model_dir = model.export(output_dir)
        assert os.path.isdir(saved_model_dir)
        assert os.path.isfile(os.path.join(saved_model_dir, "saved_model.pb"))

        # Reload the saved model
        reload_model = model_factory.load_model(model_name, saved_model_dir, framework, 'text_classification',
                                                model_hub)

        # Evaluate
        reload_metrics = reload_model.evaluate(dataset)
        assert reload_metrics == trained_metrics

        # Predict with the raw text input
        reload_predictions = reload_model.predict(raw_text_input)
        assert (reload_predictions == predictions).all()

        # Retrain from checkpoints and verify that accuracy metric is the expected type
        retrain_model = model_factory.load_model(model_name, saved_model_dir, framework, 'text_classification',
                                                 model_hub)
        retrain_model.train(dataset, output_dir=output_dir, epochs=1, initial_checkpoints=checkpoint_dir,
                            shuffle_files=False, do_eval=False)

        retrain_metrics = retrain_model.evaluate(dataset)
        accuracy_index = next(id for id, k in enumerate(model._model.metrics_names) if 'acc' in k)
        # BERT model results are not deterministic, so the commented assertion doesn't reliably pass
        # assert retrain_metrics[accuracy_index] > trained_metrics[accuracy_index]
        assert isinstance(retrain_metrics[accuracy_index], float)

    finally:
        # Delete the temp output directory
        if os.path.exists(output_dir) and os.path.isdir(output_dir):
            shutil.rmtree(output_dir)


@pytest.mark.integration
@pytest.mark.tensorflow
@pytest.mark.parametrize('model_name, dataset_name, epochs, learning_rate, do_eval, \
                         lr_decay, accuracy, val_accuracy, lr_final',
                         [['google/bert_uncased_L-2_H-128_A-2', 'glue/sst2', 1,
                           .005, False, False, None, None, 0.005],
                          ['google/bert_uncased_L-2_H-256_A-4', 'glue/sst2',
                           1, .001, True, True, 0.34375, 0.4256, 0.001],
                          ['google/bert_uncased_L-2_H-128_A-2', 'imdb_reviews',
                           15, .005, True, True, None, None, 0.001]])
def test_tf_binary_text_classification_with_lr_options(model_name, dataset_name,
                                                       epochs, learning_rate, do_eval,
                                                       lr_decay, accuracy, val_accuracy, lr_final):
    """
    Tests transfer learning for TensorFlow binary text classification with different learning rate options
    """
    framework = 'tensorflow'
    output_dir = tempfile.mkdtemp()

    try:
        # Get the dataset
        dataset = dataset_factory.get_dataset('/tmp/data', 'text_classification', framework, dataset_name,
                                              'tf_datasets', split=["train[:4%]"], shuffle_files=False)

        # Get the model
        model = model_factory.get_model(model_name, framework)
        model.learning_rate = learning_rate
        assert model.learning_rate == learning_rate

        # Preprocess the dataset
        batch_size = 32
        dataset.preprocess(batch_size)
        dataset.shuffle_split(seed=10)

        # Train
        history = model.train(dataset, output_dir=output_dir, epochs=epochs, shuffle_files=False, do_eval=do_eval,
                              lr_decay=lr_decay, seed=10)
        assert history is not None

        # TODO: BERT model results are not deterministic (AIZOO-1222), exact assertions will not pass
        # assert history['binary_accuracy'][-1] == accuracy
        # if val_accuracy:
        #     assert history['val_binary_accuracy'][-1] == val_accuracy
        # else:
        #     assert 'val_binary_accuracy' not in history

        # Non-determinism causes this assertion to fail a small fraction of the time,
        # for now, no assertions will be checked until a workaround is implemented
        if do_eval and lr_decay:
            pass
        else:
            assert 'lr' not in history

    finally:
        # Delete the temp output directory
        if os.path.exists(output_dir) and os.path.isdir(output_dir):
            shutil.rmtree(output_dir)


@pytest.mark.integration
@pytest.mark.tensorflow
@pytest.mark.parametrize('model_name',
                         ['google/bert_uncased_L-2_H-128_A-2'])
def test_custom_dataset_workflow(model_name):
    """
    Tests the full workflow for TF text classification using a custom dataset
    """
    output_dir = tempfile.mkdtemp()
    dataset_dir = '/tmp/data'

    def label_map_func(x):
        return int(x == "spam")

    try:
        # Get the dataset
        zip_file_url = "https://archive.ics.uci.edu/static/public/228/sms+spam+collection.zip"
        sms_data_directory = os.path.join(dataset_dir, "sms_spam_collection")
        csv_file_name = "SMSSpamCollection"

        # If the SMS Spam collection csv file is not found, download and extract the file:
        if not os.path.exists(os.path.join(sms_data_directory, csv_file_name)):
            # Download the zip file with the SMS Spam collection dataset
            download_and_extract_zip_file(zip_file_url, sms_data_directory)

        dataset = dataset_factory.load_dataset(sms_data_directory, use_case="text_classification",
                                               framework="tensorflow", csv_file_name="SMSSpamCollection",
                                               class_names=["ham", "spam"], shuffle_files=False,
                                               delimiter='\t', header=False, label_map_func=label_map_func)
        # Get the model
        model = model_factory.get_model(model_name, "tensorflow")

        # Preprocess the dataset and split to get small subsets for training and validation
        dataset.shuffle_split(train_pct=0.1, val_pct=0.1, shuffle_files=False)
        dataset.preprocess(batch_size=32)
        # Train for 1 epoch
        history = model.train(dataset=dataset, output_dir=output_dir, epochs=1, seed=10, do_eval=False)
        assert history is not None

        # Evaluate
        model.evaluate(dataset)

        # export the saved model
        saved_model_dir = model.export(output_dir)

        assert os.path.isdir(saved_model_dir)
        assert os.path.isfile(os.path.join(saved_model_dir, "saved_model.pb"))

        # Reload the saved model
        reload_model = model_factory.get_model(model_name, "tensorflow")
        reload_model.load_from_directory(saved_model_dir)

        # Evaluate
        metrics = reload_model.evaluate(dataset)
        assert len(metrics) > 0

        # Quantization
        inc_output_dir = os.path.join(output_dir, "quantized", "mocked")
        os.makedirs(inc_output_dir, exist_ok=True)
        model.quantize(inc_output_dir, dataset)
        assert os.path.exists(os.path.join(inc_output_dir, "saved_model.pb"))

    finally:
        # Delete the temp output directory
        if os.path.exists(output_dir) and os.path.isdir(output_dir):
            shutil.rmtree(output_dir)