test_hf_argparser.py 13.2 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
import argparse
16
17
18
import json
import os
import tempfile
19
20
21
22
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
23
from pathlib import Path
24
from typing import List, Optional
25

26
import yaml
27

Julien Chaumond's avatar
Julien Chaumond committed
28
from transformers import HfArgumentParser, TrainingArguments
29
30
31
32
33
34
35
36
37
from transformers.hf_argparser import make_choice_type_function, string_to_bool


try:
    # For Python versions <3.8, Literal is not in typing: https://peps.python.org/pep-0586/
    from typing import Literal
except ImportError:
    # For Python 3.7
    from typing_extensions import Literal
38
39


40
41
42
43
def list_field(default=None, metadata=None):
    return field(default_factory=lambda: default, metadata=metadata)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@dataclass
class BasicExample:
    foo: int
    bar: float
    baz: str
    flag: bool


@dataclass
class WithDefaultExample:
    foo: int = 42
    baz: str = field(default="toto", metadata={"help": "help message"})


@dataclass
class WithDefaultBoolExample:
    foo: bool = False
    baz: bool = True
62
    opt: Optional[bool] = None
63
64
65
66
67
68
69


class BasicEnum(Enum):
    titi = "titi"
    toto = "toto"


70
71
72
73
74
75
class MixedTypeEnum(Enum):
    titi = "titi"
    toto = "toto"
    fourtytwo = 42


76
77
@dataclass
class EnumExample:
78
79
80
81
    foo: BasicEnum = "toto"

    def __post_init__(self):
        self.foo = BasicEnum(self.foo)
82
83


84
85
86
87
88
89
90
91
@dataclass
class MixedTypeEnumExample:
    foo: MixedTypeEnum = "toto"

    def __post_init__(self):
        self.foo = MixedTypeEnum(self.foo)


92
93
94
95
96
@dataclass
class OptionalExample:
    foo: Optional[int] = None
    bar: Optional[float] = field(default=None, metadata={"help": "help message"})
    baz: Optional[str] = None
97
98
99
100
101
102
103
104
105
106
    ces: Optional[List[str]] = list_field(default=[])
    des: Optional[List[int]] = list_field(default=[])


@dataclass
class ListExample:
    foo_int: List[int] = list_field(default=[])
    bar_int: List[int] = list_field(default=[1, 2, 3])
    foo_str: List[str] = list_field(default=["Hallo", "Bonjour", "Hello"])
    foo_float: List[float] = list_field(default=[0.1, 0.2, 0.3])
107
108


109
110
111
112
113
114
115
116
117
118
@dataclass
class RequiredExample:
    required_list: List[int] = field()
    required_str: str = field()
    required_enum: BasicEnum = field()

    def __post_init__(self):
        self.required_enum = BasicEnum(self.required_enum)


119
120
121
122
123
124
125
126
127
@dataclass
class StringLiteralAnnotationExample:
    foo: int
    required_enum: "BasicEnum" = field()
    opt: "Optional[bool]" = None
    baz: "str" = field(default="toto", metadata={"help": "help message"})
    foo_str: "List[str]" = list_field(default=["Hallo", "Bonjour", "Hello"])


128
class HfArgumentParserTest(unittest.TestCase):
129
    def argparsersEqual(self, a: argparse.ArgumentParser, b: argparse.ArgumentParser):
130
131
132
133
134
135
136
        """
        Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances.
        """
        self.assertEqual(len(a._actions), len(b._actions))
        for x, y in zip(a._actions, b._actions):
            xx = {k: v for k, v in vars(x).items() if k != "container"}
            yy = {k: v for k, v in vars(y).items() if k != "container"}
137
138
139
140
141
142
143
144

            # Choices with mixed type have custom function as "type"
            # So we need to compare results directly for equality
            if xx.get("choices", None) and yy.get("choices", None):
                for expected_choice in yy["choices"] + xx["choices"]:
                    self.assertEqual(xx["type"](expected_choice), yy["type"](expected_choice))
                del xx["type"], yy["type"]

145
146
147
148
149
150
151
152
153
            self.assertEqual(xx, yy)

    def test_basic(self):
        parser = HfArgumentParser(BasicExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--foo", type=int, required=True)
        expected.add_argument("--bar", type=float, required=True)
        expected.add_argument("--baz", type=str, required=True)
154
        expected.add_argument("--flag", type=string_to_bool, default=False, const=True, nargs="?")
155
156
        self.argparsersEqual(parser, expected)

157
158
159
160
        args = ["--foo", "1", "--baz", "quux", "--bar", "0.5"]
        (example,) = parser.parse_args_into_dataclasses(args, look_for_args_file=False)
        self.assertFalse(example.flag)

161
162
163
164
165
166
167
168
169
170
171
172
    def test_with_default(self):
        parser = HfArgumentParser(WithDefaultExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--foo", default=42, type=int)
        expected.add_argument("--baz", default="toto", type=str, help="help message")
        self.argparsersEqual(parser, expected)

    def test_with_default_bool(self):
        parser = HfArgumentParser(WithDefaultBoolExample)

        expected = argparse.ArgumentParser()
173
174
        expected.add_argument("--foo", type=string_to_bool, default=False, const=True, nargs="?")
        expected.add_argument("--baz", type=string_to_bool, default=True, const=True, nargs="?")
175
176
177
        # A boolean no_* argument always has to come after its "default: True" regular counter-part
        # and its default must be set to False
        expected.add_argument("--no_baz", action="store_false", default=False, dest="baz")
178
        expected.add_argument("--opt", type=string_to_bool, default=None)
179
180
181
        self.argparsersEqual(parser, expected)

        args = parser.parse_args([])
182
        self.assertEqual(args, Namespace(foo=False, baz=True, opt=None))
183

184
        args = parser.parse_args(["--foo", "--no_baz"])
185
186
187
188
189
190
191
192
193
194
        self.assertEqual(args, Namespace(foo=True, baz=False, opt=None))

        args = parser.parse_args(["--foo", "--baz"])
        self.assertEqual(args, Namespace(foo=True, baz=True, opt=None))

        args = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"])
        self.assertEqual(args, Namespace(foo=True, baz=True, opt=True))

        args = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"])
        self.assertEqual(args, Namespace(foo=False, baz=False, opt=False))
195
196

    def test_with_enum(self):
197
        parser = HfArgumentParser(MixedTypeEnumExample)
198
199

        expected = argparse.ArgumentParser()
200
201
202
203
204
205
        expected.add_argument(
            "--foo",
            default="toto",
            choices=["titi", "toto", 42],
            type=make_choice_type_function(["titi", "toto", 42]),
        )
206
207
208
        self.argparsersEqual(parser, expected)

        args = parser.parse_args([])
209
210
        self.assertEqual(args.foo, "toto")
        enum_ex = parser.parse_args_into_dataclasses([])[0]
211
        self.assertEqual(enum_ex.foo, MixedTypeEnum.toto)
212
213

        args = parser.parse_args(["--foo", "titi"])
214
215
        self.assertEqual(args.foo, "titi")
        enum_ex = parser.parse_args_into_dataclasses(["--foo", "titi"])[0]
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
        self.assertEqual(enum_ex.foo, MixedTypeEnum.titi)

        args = parser.parse_args(["--foo", "42"])
        self.assertEqual(args.foo, 42)
        enum_ex = parser.parse_args_into_dataclasses(["--foo", "42"])[0]
        self.assertEqual(enum_ex.foo, MixedTypeEnum.fourtytwo)

    def test_with_literal(self):
        @dataclass
        class LiteralExample:
            foo: Literal["titi", "toto", 42] = "toto"

        parser = HfArgumentParser(LiteralExample)

        expected = argparse.ArgumentParser()
        expected.add_argument(
            "--foo",
            default="toto",
            choices=("titi", "toto", 42),
            type=make_choice_type_function(["titi", "toto", 42]),
        )
        self.argparsersEqual(parser, expected)

        args = parser.parse_args([])
        self.assertEqual(args.foo, "toto")

        args = parser.parse_args(["--foo", "titi"])
        self.assertEqual(args.foo, "titi")

        args = parser.parse_args(["--foo", "42"])
        self.assertEqual(args.foo, 42)
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    def test_with_list(self):
        parser = HfArgumentParser(ListExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--foo_int", nargs="+", default=[], type=int)
        expected.add_argument("--bar_int", nargs="+", default=[1, 2, 3], type=int)
        expected.add_argument("--foo_str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str)
        expected.add_argument("--foo_float", nargs="+", default=[0.1, 0.2, 0.3], type=float)

        self.argparsersEqual(parser, expected)

        args = parser.parse_args([])
        self.assertEqual(
            args,
            Namespace(foo_int=[], bar_int=[1, 2, 3], foo_str=["Hallo", "Bonjour", "Hello"], foo_float=[0.1, 0.2, 0.3]),
        )

        args = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split())
        self.assertEqual(args, Namespace(foo_int=[1], bar_int=[2, 3], foo_str=["a", "b", "c"], foo_float=[0.1, 0.7]))

268
269
270
271
272
273
274
    def test_with_optional(self):
        parser = HfArgumentParser(OptionalExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--foo", default=None, type=int)
        expected.add_argument("--bar", default=None, type=float, help="help message")
        expected.add_argument("--baz", default=None, type=str)
275
276
        expected.add_argument("--ces", nargs="+", default=[], type=str)
        expected.add_argument("--des", nargs="+", default=[], type=int)
277
278
279
        self.argparsersEqual(parser, expected)

        args = parser.parse_args([])
280
        self.assertEqual(args, Namespace(foo=None, bar=None, baz=None, ces=[], des=[]))
281

282
283
        args = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split())
        self.assertEqual(args, Namespace(foo=12, bar=3.14, baz="42", ces=["a", "b", "c"], des=[1, 2, 3]))
284

285
286
287
288
289
290
    def test_with_required(self):
        parser = HfArgumentParser(RequiredExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--required_list", nargs="+", type=int, required=True)
        expected.add_argument("--required_str", type=str, required=True)
291
292
293
294
295
296
        expected.add_argument(
            "--required_enum",
            type=make_choice_type_function(["titi", "toto"]),
            choices=["titi", "toto"],
            required=True,
        )
297
298
        self.argparsersEqual(parser, expected)

299
300
301
302
303
    def test_with_string_literal_annotation(self):
        parser = HfArgumentParser(StringLiteralAnnotationExample)

        expected = argparse.ArgumentParser()
        expected.add_argument("--foo", type=int, required=True)
304
305
306
307
308
309
        expected.add_argument(
            "--required_enum",
            type=make_choice_type_function(["titi", "toto"]),
            choices=["titi", "toto"],
            required=True,
        )
310
311
312
313
314
        expected.add_argument("--opt", type=string_to_bool, default=None)
        expected.add_argument("--baz", default="toto", type=str, help="help message")
        expected.add_argument("--foo_str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str)
        self.argparsersEqual(parser, expected)

315
316
317
318
319
320
321
322
323
324
325
326
327
328
    def test_parse_dict(self):
        parser = HfArgumentParser(BasicExample)

        args_dict = {
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }

        parsed_args = parser.parse_dict(args_dict)[0]
        args = BasicExample(**args_dict)
        self.assertEqual(parsed_args, args)

329
330
331
332
333
334
335
336
337
338
339
340
341
    def test_parse_dict_extra_key(self):
        parser = HfArgumentParser(BasicExample)

        args_dict = {
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
            "extra": 42,
        }

        self.assertRaises(ValueError, parser.parse_dict, args_dict, allow_extra_keys=False)

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
    def test_parse_json(self):
        parser = HfArgumentParser(BasicExample)

        args_dict_for_json = {
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }
        with tempfile.TemporaryDirectory() as tmp_dir:
            temp_local_path = os.path.join(tmp_dir, "temp_json")
            os.mkdir(temp_local_path)
            with open(temp_local_path + ".json", "w+") as f:
                json.dump(args_dict_for_json, f)
            parsed_args = parser.parse_yaml_file(Path(temp_local_path + ".json"))[0]

        args = BasicExample(**args_dict_for_json)
        self.assertEqual(parsed_args, args)

    def test_parse_yaml(self):
        parser = HfArgumentParser(BasicExample)

        args_dict_for_yaml = {
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }
        with tempfile.TemporaryDirectory() as tmp_dir:
            temp_local_path = os.path.join(tmp_dir, "temp_yaml")
            os.mkdir(temp_local_path)
            with open(temp_local_path + ".yaml", "w+") as f:
                yaml.dump(args_dict_for_yaml, f)
            parsed_args = parser.parse_yaml_file(Path(temp_local_path + ".yaml"))[0]
        args = BasicExample(**args_dict_for_yaml)
        self.assertEqual(parsed_args, args)

379
380
381
    def test_integration_training_args(self):
        parser = HfArgumentParser(TrainingArguments)
        self.assertIsNotNone(parser)