test_modeling_flax_utils.py 15.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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.

import tempfile
import unittest

import numpy as np
19
from huggingface_hub import HfFolder, delete_repo, snapshot_download
20
21
from requests.exceptions import HTTPError

22
23
24
25
from transformers import BertConfig, BertModel, is_flax_available, is_torch_available
from transformers.testing_utils import (
    TOKEN,
    USER,
26
    CaptureLogger,
27
28
29
30
31
32
    is_pt_flax_cross_test,
    is_staging_test,
    require_flax,
    require_safetensors,
    require_torch,
)
33
from transformers.utils import FLAX_WEIGHTS_NAME, SAFE_WEIGHTS_NAME, logging
34
35
36
37
38
39
40
41
42
43
44
45


if is_flax_available():
    import os

    from flax.core.frozen_dict import unfreeze
    from flax.traverse_util import flatten_dict

    from transformers import FlaxBertModel

    os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.12"  # assumed parallelism: 8

46
47
48
if is_torch_available():
    import torch

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

@require_flax
@is_staging_test
class FlaxModelPushToHubTester(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._token = TOKEN
        HfFolder.save_token(TOKEN)

    @classmethod
    def tearDownClass(cls):
        try:
            delete_repo(token=cls._token, repo_id="test-model-flax")
        except HTTPError:
            pass

        try:
            delete_repo(token=cls._token, repo_id="valid_org/test-model-flax-org")
        except HTTPError:
            pass

    def test_push_to_hub(self):
        config = BertConfig(
            vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37
        )
        model = FlaxBertModel(config)
Arthur's avatar
Arthur committed
75
        model.push_to_hub("test-model-flax", token=self._token)
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

        new_model = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax")

        base_params = flatten_dict(unfreeze(model.params))
        new_params = flatten_dict(unfreeze(new_model.params))

        for key in base_params.keys():
            max_diff = (base_params[key] - new_params[key]).sum().item()
            self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")

        # Reset repo
        delete_repo(token=self._token, repo_id="test-model-flax")

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
Arthur's avatar
Arthur committed
91
            model.save_pretrained(tmp_dir, repo_id="test-model-flax", push_to_hub=True, token=self._token)
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

        new_model = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax")

        base_params = flatten_dict(unfreeze(model.params))
        new_params = flatten_dict(unfreeze(new_model.params))

        for key in base_params.keys():
            max_diff = (base_params[key] - new_params[key]).sum().item()
            self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")

    def test_push_to_hub_in_organization(self):
        config = BertConfig(
            vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37
        )
        model = FlaxBertModel(config)
Arthur's avatar
Arthur committed
107
        model.push_to_hub("valid_org/test-model-flax-org", token=self._token)
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

        new_model = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")

        base_params = flatten_dict(unfreeze(model.params))
        new_params = flatten_dict(unfreeze(new_model.params))

        for key in base_params.keys():
            max_diff = (base_params[key] - new_params[key]).sum().item()
            self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")

        # Reset repo
        delete_repo(token=self._token, repo_id="valid_org/test-model-flax-org")

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(
Arthur's avatar
Arthur committed
124
                tmp_dir, repo_id="valid_org/test-model-flax-org", push_to_hub=True, token=self._token
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
            )

        new_model = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")

        base_params = flatten_dict(unfreeze(model.params))
        new_params = flatten_dict(unfreeze(new_model.params))

        for key in base_params.keys():
            max_diff = (base_params[key] - new_params[key]).sum().item()
            self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")


def check_models_equal(model1, model2):
    models_are_equal = True
    flat_params_1 = flatten_dict(model1.params)
    flat_params_2 = flatten_dict(model2.params)
    for key in flat_params_1.keys():
        if np.sum(np.abs(flat_params_1[key] - flat_params_2[key])) > 1e-4:
            models_are_equal = False

    return models_are_equal


@require_flax
class FlaxModelUtilsTest(unittest.TestCase):
    def test_model_from_pretrained_subfolder(self):
        config = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
        model = FlaxBertModel(config)

        subfolder = "bert"
        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(os.path.join(tmp_dir, subfolder))

            with self.assertRaises(OSError):
                _ = FlaxBertModel.from_pretrained(tmp_dir)

            model_loaded = FlaxBertModel.from_pretrained(tmp_dir, subfolder=subfolder)

        self.assertTrue(check_models_equal(model, model_loaded))

    def test_model_from_pretrained_subfolder_sharded(self):
        config = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
        model = FlaxBertModel(config)

        subfolder = "bert"
        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(os.path.join(tmp_dir, subfolder), max_shard_size="10KB")

            with self.assertRaises(OSError):
                _ = FlaxBertModel.from_pretrained(tmp_dir)

            model_loaded = FlaxBertModel.from_pretrained(tmp_dir, subfolder=subfolder)

        self.assertTrue(check_models_equal(model, model_loaded))

    def test_model_from_pretrained_hub_subfolder(self):
        subfolder = "bert"
        model_id = "hf-internal-testing/tiny-random-bert-subfolder"

        with self.assertRaises(OSError):
            _ = FlaxBertModel.from_pretrained(model_id)

        model = FlaxBertModel.from_pretrained(model_id, subfolder=subfolder)

        self.assertIsNotNone(model)

    def test_model_from_pretrained_hub_subfolder_sharded(self):
        subfolder = "bert"
        model_id = "hf-internal-testing/tiny-random-bert-sharded-subfolder"
        with self.assertRaises(OSError):
            _ = FlaxBertModel.from_pretrained(model_id)

        model = FlaxBertModel.from_pretrained(model_id, subfolder=subfolder)

        self.assertIsNotNone(model)
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

    @require_safetensors
    def test_safetensors_save_and_load(self):
        model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir, safe_serialization=True)

            # No msgpack file, only a model.safetensors
            self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME)))
            self.assertFalse(os.path.isfile(os.path.join(tmp_dir, FLAX_WEIGHTS_NAME)))

            new_model = FlaxBertModel.from_pretrained(tmp_dir)

        self.assertTrue(check_models_equal(model, new_model))

    @require_flax
    @require_torch
217
    @is_pt_flax_cross_test
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    def test_safetensors_save_and_load_pt_to_flax(self):
        model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-random-bert", from_pt=True)
        pt_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert")
        with tempfile.TemporaryDirectory() as tmp_dir:
            pt_model.save_pretrained(tmp_dir)

            # Check we have a model.safetensors file
            self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME)))

            new_model = FlaxBertModel.from_pretrained(tmp_dir)

        # Check models are equal
        self.assertTrue(check_models_equal(model, new_model))

    @require_safetensors
    def test_safetensors_load_from_hub(self):
234
235
236
        """
        This test checks that we can load safetensors from a checkpoint that only has those on the Hub
        """
237
238
239
240
241
242
        flax_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only")

        # Can load from the Flax-formatted checkpoint
        safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-safetensors-only")
        self.assertTrue(check_models_equal(flax_model, safetensors_model))

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    @require_safetensors
    def test_safetensors_load_from_local(self):
        """
        This test checks that we can load safetensors from a checkpoint that only has those on the Hub
        """
        with tempfile.TemporaryDirectory() as tmp:
            location = snapshot_download("hf-internal-testing/tiny-bert-flax-only", cache_dir=tmp)
            flax_model = FlaxBertModel.from_pretrained(location)

        with tempfile.TemporaryDirectory() as tmp:
            location = snapshot_download("hf-internal-testing/tiny-bert-flax-safetensors-only", cache_dir=tmp)
            safetensors_model = FlaxBertModel.from_pretrained(location)

        self.assertTrue(check_models_equal(flax_model, safetensors_model))

258
    @require_safetensors
259
260
261
262
263
264
265
266
267
268
269
270
271
    @is_pt_flax_cross_test
    def test_safetensors_load_from_hub_from_safetensors_pt(self):
        """
        This test checks that we can load safetensors from a checkpoint that only has those on the Hub.
        saved in the "pt" format.
        """
        flax_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-msgpack")

        # Can load from the PyTorch-formatted checkpoint
        safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors")
        self.assertTrue(check_models_equal(flax_model, safetensors_model))

    @require_safetensors
272
    @require_torch
273
    @is_pt_flax_cross_test
274
    def test_safetensors_load_from_hub_from_safetensors_pt_bf16(self):
275
276
277
278
        """
        This test checks that we can load safetensors from a checkpoint that only has those on the Hub.
        saved in the "pt" format.
        """
279
280
281
282
        import torch

        model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors")
        model.to(torch.bfloat16)
283

284
        with tempfile.TemporaryDirectory() as tmp:
285
286
            model.save_pretrained(tmp)
            flax_model = FlaxBertModel.from_pretrained(tmp)
287

288
289
        # Can load from the PyTorch-formatted checkpoint
        safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-bf16")
290
291
        self.assertTrue(check_models_equal(flax_model, safetensors_model))

292
    @require_safetensors
293
294
    @is_pt_flax_cross_test
    def test_safetensors_load_from_local_from_safetensors_pt(self):
295
        """
296
297
        This test checks that we can load safetensors from a checkpoint that only has those on the Hub.
        saved in the "pt" format.
298
        """
299
300
301
        with tempfile.TemporaryDirectory() as tmp:
            location = snapshot_download("hf-internal-testing/tiny-bert-msgpack", cache_dir=tmp)
            flax_model = FlaxBertModel.from_pretrained(location)
302

303
        # Can load from the PyTorch-formatted checkpoint
304
305
        with tempfile.TemporaryDirectory() as tmp:
            location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors", cache_dir=tmp)
306
            safetensors_model = FlaxBertModel.from_pretrained(location)
307

308
        self.assertTrue(check_models_equal(flax_model, safetensors_model))
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

    @require_safetensors
    def test_safetensors_load_from_hub_msgpack_before_safetensors(self):
        """
        This test checks that we'll first download msgpack weights before safetensors
        The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch
        """
        FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-msgpack")

    @require_safetensors
    def test_safetensors_load_from_local_msgpack_before_safetensors(self):
        """
        This test checks that we'll first download msgpack weights before safetensors
        The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch
        """
        with tempfile.TemporaryDirectory() as tmp:
            location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors-msgpack", cache_dir=tmp)
            FlaxBertModel.from_pretrained(location)

328
329
330
331
332
333
334
335
336
337
338
339
    @require_safetensors
    def test_safetensors_flax_from_flax(self):
        model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only")

        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir, safe_serialization=True)
            new_model = FlaxBertModel.from_pretrained(tmp_dir)

        self.assertTrue(check_models_equal(model, new_model))

    @require_safetensors
    @require_torch
340
    @is_pt_flax_cross_test
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
    def test_safetensors_flax_from_torch(self):
        hub_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
        model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only")

        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir, safe_serialization=True)
            new_model = FlaxBertModel.from_pretrained(tmp_dir)

        self.assertTrue(check_models_equal(hub_model, new_model))

    @require_safetensors
    def test_safetensors_flax_from_sharded_msgpack_with_sharded_safetensors_local(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            path = snapshot_download(
                "hf-internal-testing/tiny-bert-flax-safetensors-msgpack-sharded", cache_dir=tmp_dir
            )

            # This should not raise even if there are two types of sharded weights
            FlaxBertModel.from_pretrained(path)

    @require_safetensors
    def test_safetensors_flax_from_sharded_msgpack_with_sharded_safetensors_hub(self):
        # This should not raise even if there are two types of sharded weights
        # This should discard the safetensors weights in favor of the msgpack sharded weights
        FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-safetensors-msgpack-sharded")
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403

    @require_safetensors
    def test_safetensors_from_pt_bf16(self):
        # This should not raise; should be able to load bf16-serialized torch safetensors without issue
        # and without torch.
        logger = logging.get_logger("transformers.modeling_flax_utils")

        with CaptureLogger(logger) as cl:
            FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-bf16")

        self.assertTrue(
            "Some of the weights of FlaxBertModel were initialized in bfloat16 precision from the model checkpoint"
            in cl.out
        )

    @require_torch
    @require_safetensors
    @is_pt_flax_cross_test
    def test_from_pt_bf16(self):
        model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only")
        model.to(torch.bfloat16)

        with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir, safe_serialization=False)

            logger = logging.get_logger("transformers.modeling_flax_utils")

            with CaptureLogger(logger) as cl:
                new_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-bf16")

            self.assertTrue(
                "Some of the weights of FlaxBertModel were initialized in bfloat16 precision from the model checkpoint"
                in cl.out
            )

            flat_params_1 = flatten_dict(new_model.params)
            for value in flat_params_1.values():
                self.assertEqual(value.dtype, "bfloat16")