file_utils.py 49.7 KB
Newer Older
Sylvain Gugger's avatar
Sylvain Gugger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# Copyright 2020 The HuggingFace Team, the AllenNLP library authors. 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.
thomwolf's avatar
thomwolf committed
14
"""
Sylvain Gugger's avatar
Sylvain Gugger committed
15
16
Utilities for working with the local dataset cache. Parts of this file is adapted from the AllenNLP library at
https://github.com/allenai/allennlp.
thomwolf's avatar
thomwolf committed
17
"""
Aymeric Augustin's avatar
Aymeric Augustin committed
18

Aymeric Augustin's avatar
Aymeric Augustin committed
19
import fnmatch
Julien Chaumond's avatar
Julien Chaumond committed
20
import io
thomwolf's avatar
thomwolf committed
21
22
import json
import os
23
import re
24
import shutil
Aymeric Augustin's avatar
Aymeric Augustin committed
25
import sys
26
import tarfile
thomwolf's avatar
thomwolf committed
27
import tempfile
28
from collections import OrderedDict
Aymeric Augustin's avatar
Aymeric Augustin committed
29
from contextlib import contextmanager
30
from dataclasses import fields
31
from functools import partial, wraps
thomwolf's avatar
thomwolf committed
32
from hashlib import sha256
33
from pathlib import Path
Julien Chaumond's avatar
Julien Chaumond committed
34
from typing import Any, BinaryIO, Dict, Optional, Tuple, Union
Aymeric Augustin's avatar
Aymeric Augustin committed
35
from urllib.parse import urlparse
36
from zipfile import ZipFile, is_zipfile
thomwolf's avatar
thomwolf committed
37

38
import numpy as np
39
40
from tqdm.auto import tqdm

Aymeric Augustin's avatar
Aymeric Augustin committed
41
42
43
import requests
from filelock import FileLock

44
from . import __version__
Lysandre Debut's avatar
Lysandre Debut committed
45
from .utils import logging
thomwolf's avatar
thomwolf committed
46

Lysandre's avatar
Lysandre committed
47

Lysandre Debut's avatar
Lysandre Debut committed
48
logger = logging.get_logger(__name__)  # pylint: disable=invalid-name
thomwolf's avatar
thomwolf committed
49

50
51
52
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES"}
ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})

thomwolf's avatar
thomwolf committed
53
try:
54
55
    USE_TF = os.environ.get("USE_TF", "AUTO").upper()
    USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
56
    if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
57
        import torch
58

59
60
        _torch_available = True  # pylint: disable=invalid-name
        logger.info("PyTorch version {} available.".format(torch.__version__))
61
    else:
62
        logger.info("Disabling PyTorch because USE_TF is set")
63
        _torch_available = False
thomwolf's avatar
thomwolf committed
64
65
66
except ImportError:
    _torch_available = False  # pylint: disable=invalid-name

Lysandre's avatar
Lysandre committed
67
try:
68
69
70
    USE_TF = os.environ.get("USE_TF", "AUTO").upper()
    USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()

71
    if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
thomwolf's avatar
thomwolf committed
72
        import tensorflow as tf
73
74

        assert hasattr(tf, "__version__") and int(tf.__version__[0]) >= 2
thomwolf's avatar
thomwolf committed
75
76
77
        _tf_available = True  # pylint: disable=invalid-name
        logger.info("TensorFlow version {} available.".format(tf.__version__))
    else:
78
        logger.info("Disabling Tensorflow because USE_TORCH is set")
thomwolf's avatar
thomwolf committed
79
        _tf_available = False
Lysandre's avatar
Lysandre committed
80
81
except (ImportError, AssertionError):
    _tf_available = False  # pylint: disable=invalid-name
thomwolf's avatar
thomwolf committed
82

83

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
try:
    USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()

    if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
        import flax
        import jax

        logger.info("JAX version {}, Flax: available".format(jax.__version__))
        logger.info("Flax available: {}".format(flax))
        _flax_available = True
    else:
        _flax_available = False
except ImportError:
    _flax_available = False  # pylint: disable=invalid-name


100
try:
101
    import datasets  # noqa: F401
102

103
104
105
    # Check we're not importing a "datasets" directory somewhere
    _datasets_available = hasattr(datasets, "__version__") and hasattr(datasets, "load_dataset")
    if _datasets_available:
106
        logger.debug(f"Successfully imported datasets version {datasets.__version__}")
107
108
    else:
        logger.debug("Imported a datasets object but this doesn't seem to be the 🤗 datasets library.")
109
110

except ImportError:
111
    _datasets_available = False
112

113
114
try:
    from torch.hub import _get_torch_home
115

116
117
118
    torch_cache_home = _get_torch_home()
except ImportError:
    torch_cache_home = os.path.expanduser(
119
120
        os.getenv("TORCH_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "torch"))
    )
121
122
123


try:
124
    import torch_xla.core.xla_model as xm  # noqa: F401
125
126
127
128
129
130
131
132
133

    if _torch_available:
        _torch_tpu_available = True  # pylint: disable=
    else:
        _torch_tpu_available = False
except ImportError:
    _torch_tpu_available = False


Patrick von Platen's avatar
Patrick von Platen committed
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
try:
    import psutil  # noqa: F401

    _psutil_available = True

except ImportError:
    _psutil_available = False


try:
    import py3nvml  # noqa: F401

    _py3nvml_available = True

except ImportError:
    _py3nvml_available = False


try:
    from apex import amp  # noqa: F401

    _has_apex = True
except ImportError:
    _has_apex = False

Ola Piktus's avatar
Ola Piktus committed
159
160
161
162
163

try:
    import faiss  # noqa: F401

    _faiss_available = True
164
    logger.debug(f"Successfully imported faiss version {faiss.__version__}")
Ola Piktus's avatar
Ola Piktus committed
165
166
167
except ImportError:
    _faiss_available = False

168
169
170
171
172
173
174
175
176
try:
    import sklearn.metrics  # noqa: F401

    import scipy.stats  # noqa: F401

    _has_sklearn = True
except (AttributeError, ImportError):
    _has_sklearn = False

177
178
179
180
181
182
183
184
185
186
187
try:
    # Test copied from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
    get_ipython = sys.modules["IPython"].get_ipython
    if "IPKernelApp" not in get_ipython().config:
        raise ImportError("console")
    if "VSCODE_PID" in os.environ:
        raise ImportError("vscode")

    import IPython  # noqa: F401

    _in_notebook = True
188
except (AttributeError, ImportError, KeyError):
189
190
    _in_notebook = False

Ola Piktus's avatar
Ola Piktus committed
191

192
193
194
195
196
197
198
199
200
try:
    import sentencepiece  # noqa: F401

    _sentencepiece_available = True

except ImportError:
    _sentencepiece_available = False


201
202
203
204
205
206
207
208
209
try:
    import google.protobuf  # noqa: F401

    _protobuf_available = True

except ImportError:
    _protobuf_available = False


210
211
212
213
214
215
216
217
218
try:
    import tokenizers  # noqa: F401

    _tokenizers_available = True

except ImportError:
    _tokenizers_available = False


NielsRogge's avatar
NielsRogge committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
try:
    import pandas  # noqa: F401

    _pandas_available = True

except ImportError:
    _pandas_available = False


try:
    import torch_scatter

    # Check we're not importing a "torch_scatter" directory somewhere
    _scatter_available = hasattr(torch_scatter, "__version__") and hasattr(torch_scatter, "scatter")
    if _scatter_available:
        logger.debug(f"Succesfully imported torch-scatter version {torch_scatter.__version__}")
    else:
        logger.debug("Imported a torch_scatter object but this doesn't seem to be the torch-scatter library.")

except ImportError:
    _scatter_available = False


242
243
244
245
246
247
248
249
250
251
old_default_cache_path = os.path.join(torch_cache_home, "transformers")
# New default cache, shared with the Datasets library
hf_cache_home = os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
default_cache_path = os.path.join(hf_cache_home, "transformers")

# Onetime move from the old location to the new one if no ENV variable has been set.
if (
    os.path.isdir(old_default_cache_path)
252
    and not os.path.isdir(default_cache_path)
253
254
255
256
257
258
259
260
261
262
263
264
    and "PYTORCH_PRETRAINED_BERT_CACHE" not in os.environ
    and "PYTORCH_TRANSFORMERS_CACHE" not in os.environ
    and "TRANSFORMERS_CACHE" not in os.environ
):
    logger.warn(
        "In Transformers v4.0.0, the default path to cache downloaded models changed from "
        "'~/.cache/torch/transformers' to '~/.cache/huggingface/transformers'. Since you don't seem to have overridden "
        "and '~/.cache/torch/transformers' is a directory that exists, we're moving it to "
        "'~/.cache/huggingface/transformers' to avoid redownloading models you have already in the cache. You should "
        "only see this message once."
    )
    shutil.move(old_default_cache_path, default_cache_path)
265

266
267
268
PYTORCH_PRETRAINED_BERT_CACHE = os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path)
PYTORCH_TRANSFORMERS_CACHE = os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE)
TRANSFORMERS_CACHE = os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE)
thomwolf's avatar
thomwolf committed
269

270
WEIGHTS_NAME = "pytorch_model.bin"
271
272
TF2_WEIGHTS_NAME = "tf_model.h5"
TF_WEIGHTS_NAME = "model.ckpt"
273
FLAX_WEIGHTS_NAME = "flax_model.msgpack"
274
CONFIG_NAME = "config.json"
275
MODEL_CARD_NAME = "modelcard.json"
Thomas Wolf's avatar
Thomas Wolf committed
276

277
278
SENTENCEPIECE_UNDERLINE = "▁"
SPIECE_UNDERLINE = SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility
Lysandre's avatar
Lysandre committed
279

280
281
282
MULTIPLE_CHOICE_DUMMY_INPUTS = [
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
283
284
285
DUMMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
DUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]

286
S3_BUCKET_PREFIX = "https://s3.amazonaws.com/models.huggingface.co/bert"
Julien Chaumond's avatar
Julien Chaumond committed
287
CLOUDFRONT_DISTRIB_PREFIX = "https://cdn.huggingface.co"
Julien Chaumond's avatar
Julien Chaumond committed
288
289
HUGGINGFACE_CO_PREFIX = "https://huggingface.co/{model_id}/resolve/{revision}/{filename}"

290
291
292
293
PRESET_MIRROR_DICT = {
    "tuna": "https://mirrors.tuna.tsinghua.edu.cn/hugging-face-models",
    "bfsu": "https://mirrors.bfsu.edu.cn/hugging-face-models",
}
294

Thomas Wolf's avatar
Thomas Wolf committed
295

thomwolf's avatar
thomwolf committed
296
297
298
def is_torch_available():
    return _torch_available

299

thomwolf's avatar
thomwolf committed
300
301
302
def is_tf_available():
    return _tf_available

303

304
305
306
307
def is_flax_available():
    return _flax_available


308
309
310
311
def is_torch_tpu_available():
    return _torch_tpu_available


312
313
def is_datasets_available():
    return _datasets_available
314
315


Patrick von Platen's avatar
Patrick von Platen committed
316
317
318
319
320
321
322
323
324
325
326
327
def is_psutil_available():
    return _psutil_available


def is_py3nvml_available():
    return _py3nvml_available


def is_apex_available():
    return _has_apex


Ola Piktus's avatar
Ola Piktus committed
328
329
330
331
def is_faiss_available():
    return _faiss_available


332
333
334
335
336
337
338
339
def is_sklearn_available():
    return _has_sklearn


def is_sentencepiece_available():
    return _sentencepiece_available


340
341
342
343
def is_protobuf_available():
    return _protobuf_available


344
345
346
347
def is_tokenizers_available():
    return _tokenizers_available


348
349
350
351
def is_in_notebook():
    return _in_notebook


NielsRogge's avatar
NielsRogge committed
352
353
354
355
356
357
358
359
def is_scatter_available():
    return _scatter_available


def is_pandas_available():
    return _pandas_available


360
361
362
363
364
365
366
367
368
369
370
371
372
def torch_only_method(fn):
    def wrapper(*args, **kwargs):
        if not _torch_available:
            raise ImportError(
                "You need to install pytorch to use this method or class, "
                "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
            )
        else:
            return fn(*args, **kwargs)

    return wrapper


373
# docstyle-ignore
374
DATASETS_IMPORT_ERROR = """
375
{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
```
pip install datasets
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install datasets
```
then restarting your kernel.

Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
that python file if that's the case.
"""


391
# docstyle-ignore
392
TOKENIZERS_IMPORT_ERROR = """
393
{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
394
395
396
397
398
399
400
401
402
403
```
pip install tokenizers
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install tokenizers
```
"""


404
# docstyle-ignore
405
SENTENCEPIECE_IMPORT_ERROR = """
406
{0} requires the SentencePiece library but it was not found in your environment. Checkout the instructions on the
407
installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
408
that match your environment.
409
410
411
"""


412
413
414
415
416
417
418
419
# docstyle-ignore
PROTOBUF_IMPORT_ERROR = """
{0} requires the protobuf library but it was not found in your environment. Checkout the instructions on the
installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
that match your environment.
"""


420
# docstyle-ignore
421
FAISS_IMPORT_ERROR = """
422
{0} requires the faiss library but it was not found in your environment. Checkout the instructions on the
423
installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
424
that match your environment.
425
426
427
"""


428
# docstyle-ignore
429
PYTORCH_IMPORT_ERROR = """
430
431
{0} requires the PyTorch library but it was not found in your environment. Checkout the instructions on the
installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
432
433
434
"""


435
# docstyle-ignore
436
SKLEARN_IMPORT_ERROR = """
437
{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
438
439
440
441
442
443
444
445
446
447
```
pip install -U scikit-learn
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install -U scikit-learn
```
"""


448
# docstyle-ignore
449
TENSORFLOW_IMPORT_ERROR = """
450
451
{0} requires the TensorFlow library but it was not found in your environment. Checkout the instructions on the
installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
452
453
454
"""


455
# docstyle-ignore
456
FLAX_IMPORT_ERROR = """
457
458
{0} requires the FLAX library but it was not found in your environment. Checkout the instructions on the
installation page: https://github.com/google/flax and follow the ones that match your environment.
459
460
461
"""


NielsRogge's avatar
NielsRogge committed
462
463
464
465
466
467
468
# docstyle-ignore
SCATTER_IMPORT_ERROR = """
{0} requires the torch-scatter library but it was not found in your environment. You can install it with pip as
explained here: https://github.com/rusty1s/pytorch_scatter.
"""


469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def requires_datasets(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_datasets_available():
        raise ImportError(DATASETS_IMPORT_ERROR.format(name))


def requires_faiss(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_faiss_available():
        raise ImportError(FAISS_IMPORT_ERROR.format(name))


def requires_pytorch(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_torch_available():
        raise ImportError(PYTORCH_IMPORT_ERROR.format(name))


def requires_sklearn(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_sklearn_available():
        raise ImportError(SKLEARN_IMPORT_ERROR.format(name))


def requires_tf(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_tf_available():
        raise ImportError(TENSORFLOW_IMPORT_ERROR.format(name))
497
498


499
500
501
502
503
504
def requires_flax(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_flax_available():
        raise ImportError(FLAX_IMPORT_ERROR.format(name))


505
506
507
508
509
510
511
512
513
514
def requires_tokenizers(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_tokenizers_available():
        raise ImportError(TOKENIZERS_IMPORT_ERROR.format(name))


def requires_sentencepiece(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_sentencepiece_available():
        raise ImportError(SENTENCEPIECE_IMPORT_ERROR.format(name))
515
516


517
518
519
520
521
522
def requires_protobuf(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_protobuf_available():
        raise ImportError(PROTOBUF_IMPORT_ERROR.format(name))


NielsRogge's avatar
NielsRogge committed
523
524
525
526
527
528
def requires_scatter(obj):
    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    if not is_scatter_available():
        raise ImportError(SCATTER_IMPORT_ERROR.format(name))


Aymeric Augustin's avatar
Aymeric Augustin committed
529
530
def add_start_docstrings(*docstr):
    def docstring_decorator(fn):
531
532
533
534
535
536
        fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
        return fn

    return docstring_decorator


537
def add_start_docstrings_to_model_forward(*docstr):
538
539
540
    def docstring_decorator(fn):
        class_name = ":class:`~transformers.{}`".format(fn.__qualname__.split(".")[0])
        intro = "   The {} forward method, overrides the :func:`__call__` special method.".format(class_name)
Lysandre's avatar
Lysandre committed
541
542
        note = r"""

543
    .. note::
Sylvain Gugger's avatar
Sylvain Gugger committed
544
545
546
        Although the recipe for forward pass needs to be defined within this function, one should call the
        :class:`Module` instance afterwards instead of this since the former takes care of running the pre and post
        processing steps while the latter silently ignores them.
547
548
        """
        fn.__doc__ = intro + note + "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
Aymeric Augustin's avatar
Aymeric Augustin committed
549
        return fn
550

Aymeric Augustin's avatar
Aymeric Augustin committed
551
    return docstring_decorator
552

553

Aymeric Augustin's avatar
Aymeric Augustin committed
554
555
556
557
def add_end_docstrings(*docstr):
    def docstring_decorator(fn):
        fn.__doc__ = fn.__doc__ + "".join(docstr)
        return fn
558

Aymeric Augustin's avatar
Aymeric Augustin committed
559
    return docstring_decorator
thomwolf's avatar
thomwolf committed
560

561

Sylvain Gugger's avatar
Sylvain Gugger committed
562
PT_RETURN_INTRODUCTION = r"""
563
    Returns:
Sylvain Gugger's avatar
Sylvain Gugger committed
564
565
566
        :class:`~{full_output_type}` or :obj:`tuple(torch.FloatTensor)`: A :class:`~{full_output_type}` (if
        ``return_dict=True`` is passed or when ``config.return_dict=True``) or a tuple of :obj:`torch.FloatTensor`
        comprising various elements depending on the configuration (:class:`~transformers.{config_class}`) and inputs.
567

568
569
570
"""


Sylvain Gugger's avatar
Sylvain Gugger committed
571
572
TF_RETURN_INTRODUCTION = r"""
    Returns:
Sylvain Gugger's avatar
Sylvain Gugger committed
573
574
575
        :class:`~{full_output_type}` or :obj:`tuple(tf.Tensor)`: A :class:`~{full_output_type}` (if
        ``return_dict=True`` is passed or when ``config.return_dict=True``) or a tuple of :obj:`tf.Tensor` comprising
        various elements depending on the configuration (:class:`~transformers.{config_class}`) and inputs.
Sylvain Gugger's avatar
Sylvain Gugger committed
576
577
578
579

"""


580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def _get_indent(t):
    """Returns the indentation in the first line of t"""
    search = re.search(r"^(\s*)\S", t)
    return "" if search is None else search.groups()[0]


def _convert_output_args_doc(output_args_doc):
    """Convert output_args_doc to display properly."""
    # Split output_arg_doc in blocks argument/description
    indent = _get_indent(output_args_doc)
    blocks = []
    current_block = ""
    for line in output_args_doc.split("\n"):
        # If the indent is the same as the beginning, the line is the name of new arg.
        if _get_indent(line) == indent:
            if len(current_block) > 0:
                blocks.append(current_block[:-1])
            current_block = f"{line}\n"
        else:
            # Otherwise it's part of the description of the current arg.
            # We need to remove 2 spaces to the indentation.
            current_block += f"{line[2:]}\n"
    blocks.append(current_block[:-1])

    # Format each block for proper rendering
    for i in range(len(blocks)):
        blocks[i] = re.sub(r"^(\s+)(\S+)(\s+)", r"\1- **\2**\3", blocks[i])
        blocks[i] = re.sub(r":\s*\n\s*(\S)", r" -- \1", blocks[i])

    return "\n".join(blocks)


612
613
614
615
616
617
618
619
620
621
622
623
624
def _prepare_output_docstrings(output_type, config_class):
    """
    Prepares the return part of the docstring using `output_type`.
    """
    docstrings = output_type.__doc__

    # Remove the head of the docstring to keep the list of args only
    lines = docstrings.split("\n")
    i = 0
    while i < len(lines) and re.search(r"^\s*(Args|Parameters):\s*$", lines[i]) is None:
        i += 1
    if i < len(lines):
        docstrings = "\n".join(lines[(i + 1) :])
625
        docstrings = _convert_output_args_doc(docstrings)
626
627

    # Add the return introduction
628
    full_output_type = f"{output_type.__module__}.{output_type.__name__}"
Sylvain Gugger's avatar
Sylvain Gugger committed
629
630
    intro = TF_RETURN_INTRODUCTION if output_type.__name__.startswith("TF") else PT_RETURN_INTRODUCTION
    intro = intro.format(full_output_type=full_output_type, config_class=config_class)
631
632
633
    return intro + docstrings


634
635
636
637
638
639
640
PT_TOKEN_CLASSIFICATION_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
641
        >>> model = {model_class}.from_pretrained('{checkpoint}')
642
643
644
645
646

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> labels = torch.tensor([1] * inputs["input_ids"].size(1)).unsqueeze(0)  # Batch size 1

        >>> outputs = model(**inputs, labels=labels)
647
648
        >>> loss = outputs.loss
        >>> logits = outputs.logits
649
650
651
652
653
654
655
656
657
"""

PT_QUESTION_ANSWERING_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
658
        >>> model = {model_class}.from_pretrained('{checkpoint}')
659

660
661
        >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
        >>> inputs = tokenizer(question, text, return_tensors='pt')
662
663
664
665
        >>> start_positions = torch.tensor([1])
        >>> end_positions = torch.tensor([3])

        >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions)
666
        >>> loss = outputs.loss
667
668
        >>> start_scores = outputs.start_logits
        >>> end_scores = outputs.end_logits
669
670
671
672
673
674
675
676
677
"""

PT_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
678
        >>> model = {model_class}.from_pretrained('{checkpoint}')
679
680
681
682

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> labels = torch.tensor([1]).unsqueeze(0)  # Batch size 1
        >>> outputs = model(**inputs, labels=labels)
683
684
        >>> loss = outputs.loss
        >>> logits = outputs.logits
685
686
687
688
689
690
691
692
693
"""

PT_MASKED_LM_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
694
        >>> model = {model_class}.from_pretrained('{checkpoint}')
695

Sylvain Gugger's avatar
Sylvain Gugger committed
696
697
        >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="pt")
        >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
698

Sylvain Gugger's avatar
Sylvain Gugger committed
699
        >>> outputs = model(**inputs, labels=labels)
700
        >>> loss = outputs.loss
Sylvain Gugger's avatar
Sylvain Gugger committed
701
        >>> logits = outputs.logits
702
703
704
705
706
707
708
709
710
"""

PT_BASE_MODEL_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
711
        >>> model = {model_class}.from_pretrained('{checkpoint}')
712
713
714
715

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

716
        >>> last_hidden_states = outputs.last_hidden_state
717
718
719
720
721
722
723
724
725
"""

PT_MULTIPLE_CHOICE_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import torch

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
726
        >>> model = {model_class}.from_pretrained('{checkpoint}')
727
728
729
730
731
732

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> choice0 = "It is eaten with a fork and a knife."
        >>> choice1 = "It is eaten while held in the hand."
        >>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

733
        >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='pt', padding=True)
734
735
736
        >>> outputs = model(**{{k: v.unsqueeze(0) for k,v in encoding.items()}}, labels=labels)  # batch size is 1

        >>> # the linear classifier still needs to be trained
737
738
        >>> loss = outputs.loss
        >>> logits = outputs.logits
739
740
741
742
743
744
745
746
747
"""

PT_CAUSAL_LM_SAMPLE = r"""
    Example::

        >>> import torch
        >>> from transformers import {tokenizer_class}, {model_class}

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
748
        >>> model = {model_class}.from_pretrained('{checkpoint})
749
750
751

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs, labels=inputs["input_ids"])
752
753
        >>> loss = outputs.loss
        >>> logits = outputs.logits
754
755
756
757
758
759
760
761
762
"""

TF_TOKEN_CLASSIFICATION_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
763
        >>> model = {model_class}.from_pretrained('{checkpoint}')
764
765
766
767
768
769

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
        >>> input_ids = inputs["input_ids"]
        >>> inputs["labels"] = tf.reshape(tf.constant([1] * tf.size(input_ids).numpy()), (-1, tf.size(input_ids))) # Batch size 1

        >>> outputs = model(inputs)
Sylvain Gugger's avatar
Sylvain Gugger committed
770
771
        >>> loss = outputs.loss
        >>> logits = outputs.logits
772
773
774
775
776
777
778
779
780
"""

TF_QUESTION_ANSWERING_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
781
        >>> model = {model_class}.from_pretrained('{checkpoint}')
782
783
784

        >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
        >>> input_dict = tokenizer(question, text, return_tensors='tf')
Sylvain Gugger's avatar
Sylvain Gugger committed
785
786
787
        >>> outputs = model(input_dict)
        >>> start_logits = outputs.start_logits
        >>> end_logits = outputs.end_logits
788
789

        >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict["input_ids"].numpy()[0])
Sylvain Gugger's avatar
Sylvain Gugger committed
790
        >>> answer = ' '.join(all_tokens[tf.math.argmax(start_logits, 1)[0] : tf.math.argmax(end_logits, 1)[0]+1])
791
792
793
794
795
796
797
798
799
"""

TF_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
800
        >>> model = {model_class}.from_pretrained('{checkpoint}')
801
802
803
804
805

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
        >>> inputs["labels"] = tf.reshape(tf.constant(1), (-1, 1)) # Batch size 1

        >>> outputs = model(inputs)
Sylvain Gugger's avatar
Sylvain Gugger committed
806
807
        >>> loss = outputs.loss
        >>> logits = outputs.logits
808
809
810
811
"""

TF_MASKED_LM_SAMPLE = r"""
    Example::
Sylvain Gugger's avatar
Sylvain Gugger committed
812

813
814
815
816
        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
817
        >>> model = {model_class}.from_pretrained('{checkpoint}')
818

Sylvain Gugger's avatar
Sylvain Gugger committed
819
820
        >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="tf")
        >>> inputs["labels"] = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
821

Sylvain Gugger's avatar
Sylvain Gugger committed
822
823
824
        >>> outputs = model(inputs)
        >>> loss = outputs.loss
        >>> logits = outputs.logits
825
826
827
828
829
830
831
832
833
"""

TF_BASE_MODEL_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
834
        >>> model = {model_class}.from_pretrained('{checkpoint}')
835
836
837
838

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
        >>> outputs = model(inputs)

Sylvain Gugger's avatar
Sylvain Gugger committed
839
        >>> last_hidden_states = outputs.last_hidden_states
840
841
842
843
844
845
846
847
848
"""

TF_MULTIPLE_CHOICE_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
849
        >>> model = {model_class}.from_pretrained('{checkpoint}')
850
851
852
853
854

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> choice0 = "It is eaten with a fork and a knife."
        >>> choice1 = "It is eaten while held in the hand."

855
        >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='tf', padding=True)
856
857
858
859
        >>> inputs = {{k: tf.expand_dims(v, 0) for k, v in encoding.items()}}
        >>> outputs = model(inputs)  # batch size is 1

        >>> # the linear classifier still needs to be trained
Sylvain Gugger's avatar
Sylvain Gugger committed
860
        >>> logits = outputs.logits
861
862
863
864
865
866
867
868
869
"""

TF_CAUSAL_LM_SAMPLE = r"""
    Example::

        >>> from transformers import {tokenizer_class}, {model_class}
        >>> import tensorflow as tf

        >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}')
870
        >>> model = {model_class}.from_pretrained('{checkpoint}')
871
872
873

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
        >>> outputs = model(inputs)
Sylvain Gugger's avatar
Sylvain Gugger committed
874
        >>> logits = outputs.logits
875
876
877
"""


Sylvain Gugger's avatar
Sylvain Gugger committed
878
879
880
def add_code_sample_docstrings(
    *docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None, mask=None
):
881
882
883
    def docstring_decorator(fn):
        model_class = fn.__qualname__.split(".")[0]
        is_tf_class = model_class[:2] == "TF"
Sylvain Gugger's avatar
Sylvain Gugger committed
884
        doc_kwargs = dict(model_class=model_class, tokenizer_class=tokenizer_class, checkpoint=checkpoint)
885
886
887
888
889
890
891
892
893

        if "SequenceClassification" in model_class:
            code_sample = TF_SEQUENCE_CLASSIFICATION_SAMPLE if is_tf_class else PT_SEQUENCE_CLASSIFICATION_SAMPLE
        elif "QuestionAnswering" in model_class:
            code_sample = TF_QUESTION_ANSWERING_SAMPLE if is_tf_class else PT_QUESTION_ANSWERING_SAMPLE
        elif "TokenClassification" in model_class:
            code_sample = TF_TOKEN_CLASSIFICATION_SAMPLE if is_tf_class else PT_TOKEN_CLASSIFICATION_SAMPLE
        elif "MultipleChoice" in model_class:
            code_sample = TF_MULTIPLE_CHOICE_SAMPLE if is_tf_class else PT_MULTIPLE_CHOICE_SAMPLE
Sylvain Gugger's avatar
Sylvain Gugger committed
894
895
        elif "MaskedLM" in model_class or model_class in ["FlaubertWithLMHeadModel", "XLMWithLMHeadModel"]:
            doc_kwargs["mask"] = "[MASK]" if mask is None else mask
896
            code_sample = TF_MASKED_LM_SAMPLE if is_tf_class else PT_MASKED_LM_SAMPLE
Lysandre Debut's avatar
Lysandre Debut committed
897
        elif "LMHead" in model_class or "CausalLM" in model_class:
898
            code_sample = TF_CAUSAL_LM_SAMPLE if is_tf_class else PT_CAUSAL_LM_SAMPLE
899
        elif "Model" in model_class or "Encoder" in model_class:
900
901
902
903
            code_sample = TF_BASE_MODEL_SAMPLE if is_tf_class else PT_BASE_MODEL_SAMPLE
        else:
            raise ValueError(f"Docstring can't be built for model {model_class}")

904
        output_doc = _prepare_output_docstrings(output_type, config_class) if output_type is not None else ""
Sylvain Gugger's avatar
Sylvain Gugger committed
905
        built_doc = code_sample.format(**doc_kwargs)
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        fn.__doc__ = (fn.__doc__ or "") + "".join(docstr) + output_doc + built_doc
        return fn

    return docstring_decorator


def replace_return_docstrings(output_type=None, config_class=None):
    def docstring_decorator(fn):
        docstrings = fn.__doc__
        lines = docstrings.split("\n")
        i = 0
        while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
            i += 1
        if i < len(lines):
            lines[i] = _prepare_output_docstrings(output_type, config_class)
            docstrings = "\n".join(lines)
        else:
            raise ValueError(
                f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, current docstring is:\n{docstrings}"
            )
        fn.__doc__ = docstrings
927
928
929
930
931
        return fn

    return docstring_decorator


932
933
def is_remote_url(url_or_filename):
    parsed = urlparse(url_or_filename)
Julien Chaumond's avatar
Julien Chaumond committed
934
    return parsed.scheme in ("http", "https")
935

936

937
938
939
def hf_bucket_url(
    model_id: str, filename: str, subfolder: Optional[str] = None, revision: Optional[str] = None, mirror=None
) -> str:
Julien Chaumond's avatar
Julien Chaumond committed
940
    """
Julien Chaumond's avatar
Julien Chaumond committed
941
942
    Resolve a model identifier, a file name, and an optional revision id, to a huggingface.co-hosted url, redirecting
    to Cloudfront (a Content Delivery Network, or CDN) for large files.
Sylvain Gugger's avatar
Sylvain Gugger committed
943
944

    Cloudfront is replicated over the globe so downloads are way faster for the end user (and it also lowers our
Julien Chaumond's avatar
Julien Chaumond committed
945
946
947
948
949
950
    bandwidth costs).

    Cloudfront aggressively caches files by default (default TTL is 24 hours), however this is not an issue here
    because we migrated to a git-based versioning system on huggingface.co, so we now store the files on S3/Cloudfront
    in a content-addressable way (i.e., the file name is its hash). Using content-addressable filenames means cache
    can't ever be stale.
Sylvain Gugger's avatar
Sylvain Gugger committed
951

Julien Chaumond's avatar
Julien Chaumond committed
952
953
954
    In terms of client-side caching from this library, we base our caching on the objects' ETag. An object' ETag is:
    its sha1 if stored in git, or its sha256 if stored in git-lfs. Files cached locally from transformers before v3.5.0
    are not shared with those new files, because the cached file's name contains a hash of the url (which changed).
Julien Chaumond's avatar
Julien Chaumond committed
955
    """
956
957
958
    if subfolder is not None:
        filename = f"{subfolder}/{filename}"

Julien Chaumond's avatar
Julien Chaumond committed
959
960
961
962
963
964
965
966
967
968
969
    if mirror:
        endpoint = PRESET_MIRROR_DICT.get(mirror, mirror)
        legacy_format = "/" not in model_id
        if legacy_format:
            return f"{endpoint}/{model_id}-{filename}"
        else:
            return f"{endpoint}/{model_id}/{filename}"

    if revision is None:
        revision = "main"
    return HUGGINGFACE_CO_PREFIX.format(model_id=model_id, revision=revision, filename=filename)
970
971


Julien Chaumond's avatar
Julien Chaumond committed
972
def url_to_filename(url: str, etag: Optional[str] = None) -> str:
thomwolf's avatar
thomwolf committed
973
    """
Sylvain Gugger's avatar
Sylvain Gugger committed
974
975
976
977
    Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,
    delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
    identify it as a HDF5 file (see
    https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)
thomwolf's avatar
thomwolf committed
978
    """
979
    url_bytes = url.encode("utf-8")
Julien Chaumond's avatar
Julien Chaumond committed
980
    filename = sha256(url_bytes).hexdigest()
thomwolf's avatar
thomwolf committed
981
982

    if etag:
983
        etag_bytes = etag.encode("utf-8")
Julien Chaumond's avatar
Julien Chaumond committed
984
        filename += "." + sha256(etag_bytes).hexdigest()
thomwolf's avatar
thomwolf committed
985

986
987
    if url.endswith(".h5"):
        filename += ".h5"
thomwolf's avatar
thomwolf committed
988

thomwolf's avatar
thomwolf committed
989
990
991
    return filename


thomwolf's avatar
thomwolf committed
992
def filename_to_url(filename, cache_dir=None):
thomwolf's avatar
thomwolf committed
993
    """
Sylvain Gugger's avatar
Sylvain Gugger committed
994
995
    Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or
    its stored metadata do not exist.
thomwolf's avatar
thomwolf committed
996
997
    """
    if cache_dir is None:
998
        cache_dir = TRANSFORMERS_CACHE
999
    if isinstance(cache_dir, Path):
1000
        cache_dir = str(cache_dir)
thomwolf's avatar
thomwolf committed
1001
1002
1003

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
thomwolf's avatar
thomwolf committed
1004
        raise EnvironmentError("file {} not found".format(cache_path))
thomwolf's avatar
thomwolf committed
1005

1006
    meta_path = cache_path + ".json"
thomwolf's avatar
thomwolf committed
1007
    if not os.path.exists(meta_path):
thomwolf's avatar
thomwolf committed
1008
        raise EnvironmentError("file {} not found".format(meta_path))
thomwolf's avatar
thomwolf committed
1009

thomwolf's avatar
thomwolf committed
1010
    with open(meta_path, encoding="utf-8") as meta_file:
thomwolf's avatar
thomwolf committed
1011
        metadata = json.load(meta_file)
1012
1013
    url = metadata["url"]
    etag = metadata["etag"]
thomwolf's avatar
thomwolf committed
1014
1015
1016
1017

    return url, etag


1018
def cached_path(
1019
1020
1021
1022
1023
    url_or_filename,
    cache_dir=None,
    force_download=False,
    proxies=None,
    resume_download=False,
Julien Chaumond's avatar
Julien Chaumond committed
1024
    user_agent: Union[Dict, str, None] = None,
1025
1026
    extract_compressed_file=False,
    force_extract=False,
1027
    local_files_only=False,
1028
) -> Optional[str]:
thomwolf's avatar
thomwolf committed
1029
    """
Sylvain Gugger's avatar
Sylvain Gugger committed
1030
1031
1032
1033
    Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file
    and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and
    then return the path

1034
1035
    Args:
        cache_dir: specify a cache directory to save the file to (overwrite the default cache dir).
1036
1037
        force_download: if True, re-download the file even if it's already cached in the cache dir.
        resume_download: if True, resume the download if incompletely received file is found.
1038
        user_agent: Optional string or dict that will be appended to the user-agent on remote requests.
1039
1040
1041
        extract_compressed_file: if True and the path point to a zip or tar file, extract the compressed
            file in a folder along the archive.
        force_extract: if True when extract_compressed_file is True and the archive was already extracted,
1042
            re-extract the archive and override the folder where it was extracted.
1043
1044

    Return:
Julien Chaumond's avatar
Julien Chaumond committed
1045
1046
1047
1048
        Local path (string) of file or if networking is off, last version of file cached on disk.

    Raises:
        In case of non-recoverable file (non-existent or inaccessible url + no cache on disk).
thomwolf's avatar
thomwolf committed
1049
1050
    """
    if cache_dir is None:
1051
        cache_dir = TRANSFORMERS_CACHE
1052
    if isinstance(url_or_filename, Path):
1053
        url_or_filename = str(url_or_filename)
1054
    if isinstance(cache_dir, Path):
1055
        cache_dir = str(cache_dir)
thomwolf's avatar
thomwolf committed
1056

1057
    if is_remote_url(url_or_filename):
thomwolf's avatar
thomwolf committed
1058
        # URL, so get it from the cache (downloading if necessary)
1059
        output_path = get_from_cache(
1060
1061
1062
1063
1064
1065
            url_or_filename,
            cache_dir=cache_dir,
            force_download=force_download,
            proxies=proxies,
            resume_download=resume_download,
            user_agent=user_agent,
1066
            local_files_only=local_files_only,
1067
        )
thomwolf's avatar
thomwolf committed
1068
1069
    elif os.path.exists(url_or_filename):
        # File, and it exists.
1070
        output_path = url_or_filename
1071
    elif urlparse(url_or_filename).scheme == "":
thomwolf's avatar
thomwolf committed
1072
        # File, but it doesn't exist.
thomwolf's avatar
thomwolf committed
1073
        raise EnvironmentError("file {} not found".format(url_or_filename))
thomwolf's avatar
thomwolf committed
1074
1075
1076
1077
    else:
        # Something unknown
        raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename))

1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
    if extract_compressed_file:
        if not is_zipfile(output_path) and not tarfile.is_tarfile(output_path):
            return output_path

        # Path where we extract compressed archives
        # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
        output_dir, output_file = os.path.split(output_path)
        output_extract_dir_name = output_file.replace(".", "-") + "-extracted"
        output_path_extracted = os.path.join(output_dir, output_extract_dir_name)

        if os.path.isdir(output_path_extracted) and os.listdir(output_path_extracted) and not force_extract:
            return output_path_extracted

        # Prevent parallel extractions
        lock_path = output_path + ".lock"
        with FileLock(lock_path):
            shutil.rmtree(output_path_extracted, ignore_errors=True)
            os.makedirs(output_path_extracted)
            if is_zipfile(output_path):
                with ZipFile(output_path, "r") as zip_file:
                    zip_file.extractall(output_path_extracted)
                    zip_file.close()
            elif tarfile.is_tarfile(output_path):
                tar_file = tarfile.open(output_path)
                tar_file.extractall(output_path_extracted)
                tar_file.close()
thomwolf's avatar
cleanup  
thomwolf committed
1104
1105
            else:
                raise EnvironmentError("Archive format of {} could not be identified".format(output_path))
1106
1107
1108
1109
1110

        return output_path_extracted

    return output_path

thomwolf's avatar
thomwolf committed
1111

Julien Chaumond's avatar
Julien Chaumond committed
1112
1113
1114
1115
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
    """
    Formats a user-agent string with basic info about a request.
    """
1116
    ua = "transformers/{}; python/{}".format(__version__, sys.version.split()[0])
1117
1118
1119
1120
    if is_torch_available():
        ua += "; torch/{}".format(torch.__version__)
    if is_tf_available():
        ua += "; tensorflow/{}".format(tf.__version__)
1121
    if isinstance(user_agent, dict):
1122
        ua += "; " + "; ".join("{}/{}".format(k, v) for k, v in user_agent.items())
Aymeric Augustin's avatar
Aymeric Augustin committed
1123
    elif isinstance(user_agent, str):
1124
        ua += "; " + user_agent
Julien Chaumond's avatar
Julien Chaumond committed
1125
1126
1127
1128
1129
1130
1131
1132
    return ua


def http_get(url: str, temp_file: BinaryIO, proxies=None, resume_size=0, user_agent: Union[Dict, str, None] = None):
    """
    Donwload remote file. Do not gobble up errors.
    """
    headers = {"user-agent": http_user_agent(user_agent)}
1133
    if resume_size > 0:
1134
        headers["Range"] = "bytes=%d-" % (resume_size,)
Julien Chaumond's avatar
Julien Chaumond committed
1135
1136
1137
    r = requests.get(url, stream=True, proxies=proxies, headers=headers)
    r.raise_for_status()
    content_length = r.headers.get("Content-Length")
1138
    total = resume_size + int(content_length) if content_length is not None else None
1139
1140
1141
1142
1143
1144
    progress = tqdm(
        unit="B",
        unit_scale=True,
        total=total,
        initial=resume_size,
        desc="Downloading",
Lysandre's avatar
Lysandre committed
1145
        disable=bool(logging.get_verbosity() == logging.NOTSET),
1146
    )
Julien Chaumond's avatar
Julien Chaumond committed
1147
    for chunk in r.iter_content(chunk_size=1024):
1148
        if chunk:  # filter out keep-alive new chunks
thomwolf's avatar
thomwolf committed
1149
1150
1151
1152
1153
            progress.update(len(chunk))
            temp_file.write(chunk)
    progress.close()


1154
def get_from_cache(
Julien Chaumond's avatar
Julien Chaumond committed
1155
    url: str,
1156
1157
1158
1159
1160
    cache_dir=None,
    force_download=False,
    proxies=None,
    etag_timeout=10,
    resume_download=False,
Julien Chaumond's avatar
Julien Chaumond committed
1161
    user_agent: Union[Dict, str, None] = None,
1162
    local_files_only=False,
1163
) -> Optional[str]:
thomwolf's avatar
thomwolf committed
1164
    """
Sylvain Gugger's avatar
Sylvain Gugger committed
1165
1166
    Given a URL, look for the corresponding file in the local cache. If it's not there, download it. Then return the
    path to the cached file.
1167
1168

    Return:
Julien Chaumond's avatar
Julien Chaumond committed
1169
1170
1171
1172
        Local path (string) of file or if networking is off, last version of file cached on disk.

    Raises:
        In case of non-recoverable file (non-existent or inaccessible url + no cache on disk).
thomwolf's avatar
thomwolf committed
1173
1174
    """
    if cache_dir is None:
1175
        cache_dir = TRANSFORMERS_CACHE
1176
    if isinstance(cache_dir, Path):
1177
        cache_dir = str(cache_dir)
thomwolf's avatar
thomwolf committed
1178

1179
    os.makedirs(cache_dir, exist_ok=True)
thomwolf's avatar
thomwolf committed
1180

Julien Chaumond's avatar
Julien Chaumond committed
1181
    url_to_download = url
1182
1183
    etag = None
    if not local_files_only:
Julien Chaumond's avatar
Julien Chaumond committed
1184
        try:
Julien Chaumond's avatar
Julien Chaumond committed
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
            headers = {"user-agent": http_user_agent(user_agent)}
            r = requests.head(url, headers=headers, allow_redirects=False, proxies=proxies, timeout=etag_timeout)
            r.raise_for_status()
            etag = r.headers.get("X-Linked-Etag") or r.headers.get("ETag")
            # We favor a custom header indicating the etag of the linked resource, and
            # we fallback to the regular etag header.
            # If we don't have any of those, raise an error.
            if etag is None:
                raise OSError(
                    "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
                )
            # In case of a redirect,
            # save an extra redirect on the request.get call,
            # and ensure we download the exact atomic version even if it changed
            # between the HEAD and the GET (unlikely, but hey).
            if 300 <= r.status_code <= 399:
                url_to_download = r.headers["Location"]
        except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
Julien Chaumond's avatar
Julien Chaumond committed
1203
1204
            # etag is already None
            pass
thomwolf's avatar
thomwolf committed
1205
1206
1207
1208
1209
1210

    filename = url_to_filename(url, etag)

    # get cache path to put the file
    cache_path = os.path.join(cache_dir, filename)

Julien Chaumond's avatar
Julien Chaumond committed
1211
    # etag is None == we don't have a connection or we passed local_files_only.
1212
    # try to get the last downloaded one
1213
1214
1215
1216
1217
1218
    if etag is None:
        if os.path.exists(cache_path):
            return cache_path
        else:
            matching_files = [
                file
1219
                for file in fnmatch.filter(os.listdir(cache_dir), filename.split(".")[0] + ".*")
1220
1221
1222
1223
1224
                if not file.endswith(".json") and not file.endswith(".lock")
            ]
            if len(matching_files) > 0:
                return os.path.join(cache_dir, matching_files[-1])
            else:
1225
1226
1227
1228
1229
1230
1231
1232
1233
                # If files cannot be found and local_files_only=True,
                # the models might've been found if local_files_only=False
                # Notify the user about that
                if local_files_only:
                    raise ValueError(
                        "Cannot find the requested files in the cached path and outgoing traffic has been"
                        " disabled. To enable model look-ups and downloads online, set 'local_files_only'"
                        " to False."
                    )
Julien Chaumond's avatar
Julien Chaumond committed
1234
1235
1236
1237
1238
                else:
                    raise ValueError(
                        "Connection error, and we cannot find the requested files in the cached path."
                        " Please try again or make sure your Internet connection is on."
                    )
1239
1240
1241
1242

    # From now on, etag is not None.
    if os.path.exists(cache_path) and not force_download:
        return cache_path
1243

1244
    # Prevent parallel downloads of the same file with a lock.
1245
    lock_path = cache_path + ".lock"
1246
1247
    with FileLock(lock_path):

Julien Chaumond's avatar
Julien Chaumond committed
1248
1249
1250
1251
1252
        # If the download just completed while the lock was activated.
        if os.path.exists(cache_path) and not force_download:
            # Even if returning early like here, the lock will be released.
            return cache_path

1253
        if resume_download:
1254
1255
            incomplete_path = cache_path + ".incomplete"

1256
            @contextmanager
Julien Chaumond's avatar
Julien Chaumond committed
1257
1258
            def _resumable_file_manager() -> "io.BufferedWriter":
                with open(incomplete_path, "ab") as f:
1259
                    yield f
1260

1261
1262
1263
1264
1265
            temp_file_manager = _resumable_file_manager
            if os.path.exists(incomplete_path):
                resume_size = os.stat(incomplete_path).st_size
            else:
                resume_size = 0
1266
        else:
Julien Chaumond's avatar
Julien Chaumond committed
1267
            temp_file_manager = partial(tempfile.NamedTemporaryFile, mode="wb", dir=cache_dir, delete=False)
1268
            resume_size = 0
1269

1270
1271
1272
1273
1274
        # Download to temporary file, then copy to cache dir once finished.
        # Otherwise you get corrupt cache entries if the download gets interrupted.
        with temp_file_manager() as temp_file:
            logger.info("%s not found in cache or force_download set to True, downloading to %s", url, temp_file.name)

Julien Chaumond's avatar
Julien Chaumond committed
1275
            http_get(url_to_download, temp_file, proxies=proxies, resume_size=resume_size, user_agent=user_agent)
1276
1277

        logger.info("storing %s in cache at %s", url, cache_path)
1278
        os.replace(temp_file.name, cache_path)
1279
1280
1281
1282
1283
1284

        logger.info("creating metadata file for %s", cache_path)
        meta = {"url": url, "etag": etag}
        meta_path = cache_path + ".json"
        with open(meta_path, "w") as meta_file:
            json.dump(meta, meta_file)
thomwolf's avatar
thomwolf committed
1285
1286

    return cache_path
Julien Chaumond's avatar
Julien Chaumond committed
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333


class cached_property(property):
    """
    Descriptor that mimics @property but caches output in member variable.

    From tensorflow_datasets

    Built-in in functools from Python 3.8.
    """

    def __get__(self, obj, objtype=None):
        # See docs.python.org/3/howto/descriptor.html#properties
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        attr = "__cached_" + self.fget.__name__
        cached = getattr(obj, attr, None)
        if cached is None:
            cached = self.fget(obj)
            setattr(obj, attr, cached)
        return cached


def torch_required(func):
    # Chose a different decorator name than in tests so it's clear they are not the same.
    @wraps(func)
    def wrapper(*args, **kwargs):
        if is_torch_available():
            return func(*args, **kwargs)
        else:
            raise ImportError(f"Method `{func.__name__}` requires PyTorch.")

    return wrapper


def tf_required(func):
    # Chose a different decorator name than in tests so it's clear they are not the same.
    @wraps(func)
    def wrapper(*args, **kwargs):
        if is_tf_available():
            return func(*args, **kwargs)
        else:
            raise ImportError(f"Method `{func.__name__}` requires TF.")

    return wrapper
1334
1335


1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
def is_tensor(x):
    """ Tests if ``x`` is a :obj:`torch.Tensor`, :obj:`tf.Tensor` or :obj:`np.ndarray`. """
    if is_torch_available():
        import torch

        if isinstance(x, torch.Tensor):
            return True
    if is_tf_available():
        import tensorflow as tf

        if isinstance(x, tf.Tensor):
            return True
    return isinstance(x, np.ndarray)


class ModelOutput(OrderedDict):
1352
    """
1353
    Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like
Sylvain Gugger's avatar
Sylvain Gugger committed
1354
1355
    a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a regular
    python dictionary.
1356
1357
1358
1359

    .. warning::
        You can't unpack a :obj:`ModelOutput` directly. Use the :meth:`~transformers.file_utils.ModelOutput.to_tuple`
        method to convert it to a tuple before.
1360
1361
    """

1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
    def __post_init__(self):
        class_fields = fields(self)

        # Safety and consistency checks
        assert len(class_fields), f"{self.__class__.__name__} has no fields."
        assert all(
            field.default is None for field in class_fields[1:]
        ), f"{self.__class__.__name__} should not have more than one required field."

        first_field = getattr(self, class_fields[0].name)
        other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])

        if other_fields_are_none and not is_tensor(first_field):
            try:
                iterator = iter(first_field)
                first_field_iterator = True
            except TypeError:
                first_field_iterator = False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
            if first_field_iterator:
                for element in iterator:
                    if (
                        not isinstance(element, (list, tuple))
                        or not len(element) == 2
                        or not isinstance(element[0], str)
                    ):
                        break
                    setattr(self, element[0], element[1])
                    if element[1] is not None:
                        self[element[0]] = element[1]
1394
1395
            elif first_field is not None:
                self[class_fields[0].name] = first_field
1396
1397
1398
1399
1400
        else:
            for field in class_fields:
                v = getattr(self, field.name)
                if v is not None:
                    self[field.name] = v
1401

1402
1403
    def __delitem__(self, *args, **kwargs):
        raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
1404

1405
1406
    def setdefault(self, *args, **kwargs):
        raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
1407

1408
1409
1410
1411
1412
    def pop(self, *args, **kwargs):
        raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")

    def update(self, *args, **kwargs):
        raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
1413

1414
1415
1416
1417
1418
1419
    def __getitem__(self, k):
        if isinstance(k, str):
            inner_dict = {k: v for (k, v) in self.items()}
            return inner_dict[k]
        else:
            return self.to_tuple()[k]
1420

1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
    def __setattr__(self, name, value):
        if name in self.keys() and value is not None:
            # Don't call self.__setitem__ to avoid recursion errors
            super().__setitem__(name, value)
        super().__setattr__(name, value)

    def __setitem__(self, key, value):
        # Will raise a KeyException if needed
        super().__setitem__(key, value)
        # Don't call self.__setattr__ to avoid recursion errors
        super().__setattr__(key, value)

1433
1434
1435
1436
1437
    def to_tuple(self) -> Tuple[Any]:
        """
        Convert self to a tuple containing all the attributes/keys that are not ``None``.
        """
        return tuple(self[k] for k in self.keys())