test_configuration_auto.py 6.58 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team.
#
# 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.

16
import importlib
17
18
import json
import os
19
import sys
20
import tempfile
21
import unittest
22
from pathlib import Path
23

24
import transformers
25
import transformers.models.auto
Sylvain Gugger's avatar
Sylvain Gugger committed
26
27
28
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
Yih-Dar's avatar
Yih-Dar committed
29
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
Julien Chaumond's avatar
Julien Chaumond committed
30

31

Yih-Dar's avatar
Yih-Dar committed
32
sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
33
34

from test_module.custom_configuration import CustomConfig  # noqa E402
35
36


Yih-Dar's avatar
Yih-Dar committed
37
SAMPLE_ROBERTA_CONFIG = get_tests_dir("fixtures/dummy-config.json")
38
39


40
class AutoConfigTest(unittest.TestCase):
41
42
43
    def setUp(self):
        transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0

44
45
46
47
    def test_module_spec(self):
        self.assertIsNotNone(transformers.models.auto.__spec__)
        self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"))

48
    def test_config_from_model_shortcut(self):
49
        config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
50
51
        self.assertIsInstance(config, BertConfig)

Julien Chaumond's avatar
Julien Chaumond committed
52
    def test_config_model_type_from_local_file(self):
53
54
55
        config = AutoConfig.from_pretrained(SAMPLE_ROBERTA_CONFIG)
        self.assertIsInstance(config, RobertaConfig)

Julien Chaumond's avatar
Julien Chaumond committed
56
    def test_config_model_type_from_model_identifier(self):
57
        config = AutoConfig.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER)
Julien Chaumond's avatar
Julien Chaumond committed
58
59
        self.assertIsInstance(config, RobertaConfig)

60
61
62
    def test_config_for_model_str(self):
        config = AutoConfig.for_model("roberta")
        self.assertIsInstance(config, RobertaConfig)
63
64

    def test_pattern_matching_fallback(self):
65
66
67
68
69
70
71
72
        with tempfile.TemporaryDirectory() as tmp_dir:
            # This model name contains bert and roberta, but roberta ends up being picked.
            folder = os.path.join(tmp_dir, "fake-roberta")
            os.makedirs(folder, exist_ok=True)
            with open(os.path.join(folder, "config.json"), "w") as f:
                f.write(json.dumps({}))
            config = AutoConfig.from_pretrained(folder)
            self.assertEqual(type(config), RobertaConfig)
73
74
75

    def test_new_config_registration(self):
        try:
76
            AutoConfig.register("custom", CustomConfig)
77
78
            # Wrong model type will raise an error
            with self.assertRaises(ValueError):
79
                AutoConfig.register("model", CustomConfig)
80
81
82
83
84
            # Trying to register something existing in the Transformers library will raise an error
            with self.assertRaises(ValueError):
                AutoConfig.register("bert", BertConfig)

            # Now that the config is registered, it can be used as any other config with the auto-API
85
            config = CustomConfig()
86
87
88
            with tempfile.TemporaryDirectory() as tmp_dir:
                config.save_pretrained(tmp_dir)
                new_config = AutoConfig.from_pretrained(tmp_dir)
89
                self.assertIsInstance(new_config, CustomConfig)
90
91

        finally:
92
93
            if "custom" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["custom"]
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

    def test_repo_not_found(self):
        with self.assertRaisesRegex(
            EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
        ):
            _ = AutoConfig.from_pretrained("bert-base")

    def test_revision_not_found(self):
        with self.assertRaisesRegex(
            EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
        ):
            _ = AutoConfig.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")

    def test_configuration_not_found(self):
        with self.assertRaisesRegex(
            EnvironmentError,
            "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.",
        ):
            _ = AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo")
113
114

    def test_from_pretrained_dynamic_config(self):
115
116
117
118
119
120
121
        # If remote code is not set, we will time out when asking whether to load the model.
        with self.assertRaises(ValueError):
            config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
        # If remote code is disabled, we can't load this config.
        with self.assertRaises(ValueError):
            config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)

122
123
        config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
        self.assertEqual(config.__class__.__name__, "NewModelConfig")
124
125
126
127
128
129

        # Test config can be reloaded.
        with tempfile.TemporaryDirectory() as tmp_dir:
            config.save_pretrained(tmp_dir)
            reloaded_config = AutoConfig.from_pretrained(tmp_dir, trust_remote_code=True)
        self.assertEqual(reloaded_config.__class__.__name__, "NewModelConfig")
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

    def test_from_pretrained_dynamic_config_conflict(self):
        class NewModelConfigLocal(BertConfig):
            model_type = "new-model"

        try:
            AutoConfig.register("new-model", NewModelConfigLocal)
            # If remote code is not set, the default is to use local
            config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
            self.assertEqual(config.__class__.__name__, "NewModelConfigLocal")

            # If remote code is disabled, we load the local one.
            config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)
            self.assertEqual(config.__class__.__name__, "NewModelConfigLocal")

            # If remote is enabled, we load from the Hub
            config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
            self.assertEqual(config.__class__.__name__, "NewModelConfig")

        finally:
            if "new-model" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["new-model"]