





'''simple docstring'''


import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					Dict=False    ):



    '''simple docstring'''





    try:
        _lowerCAmelCase				=      os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        _lowerCAmelCase				=      default
    else:
        # KEY is set, convert it to True or False.
        try:
            _lowerCAmelCase				=      strtobool(SCREAMING_SNAKE_CASE_    )
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(F'''If set, {key} must be yes or no.'''    )
    return _value


_SCREAMING_SNAKE_CASE	 =							parse_flag_from_env("RUN_SLOW", default=False)


def 	__a(SCREAMING_SNAKE_CASE_  :					List[str]    ):



    '''simple docstring'''





    return unittest.skip("Test was skipped"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(_run_slow_tests		,       "test is slow"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Any    ):



    '''simple docstring'''





    return unittest.skipUnless(not torch.cuda.is_available()		,       "test requires only a CPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(torch.cuda.is_available()		,       "test requires a GPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict    ):



    '''simple docstring'''





    return unittest.skipUnless(is_xpu_available()		,       "test requires a XPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(is_mps_available()		,       "test requires a `mps` backend support in `torch`"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					int    ):



    '''simple docstring'''





    return unittest.skipUnless(
        is_transformers_available() and is_datasets_available()		,       "test requires the Hugging Face suite"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Any    ):



    '''simple docstring'''





    return unittest.skipUnless(is_bnb_available()		,       "test requires the bitsandbytes library"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[str]    ):



    '''simple docstring'''





    return unittest.skipUnless(is_tpu_available()		,       "test requires TPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(torch.cuda.device_count() == 1		,       "test requires a GPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(torch.xpu.device_count() == 1		,       "test requires a XPU"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Union[str, Any]    ):



    '''simple docstring'''





    return unittest.skipUnless(torch.cuda.device_count() > 1		,       "test requires multiple GPUs"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict    ):



    '''simple docstring'''





    return unittest.skipUnless(torch.xpu.device_count() > 1		,       "test requires multiple XPUs"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return unittest.skipUnless(is_safetensors_available()		,       "test requires safetensors"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Any    ):



    '''simple docstring'''





    return unittest.skipUnless(is_deepspeed_available()		,       "test requires DeepSpeed"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return unittest.skipUnless(is_torch_version(">="		,       "1.12.0"    )		,       "test requires torch version >= 1.12.0"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[str]=None		,       SCREAMING_SNAKE_CASE_  :					Tuple=None    ):



    '''simple docstring'''





    if test_case is None:
        return partial(SCREAMING_SNAKE_CASE_		,       version=SCREAMING_SNAKE_CASE_    )
    return unittest.skipUnless(is_torch_version(">="		,       SCREAMING_SNAKE_CASE_    )		,       F'''test requires torch version >= {version}'''    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return unittest.skipUnless(is_tensorboard_available()		,       "test requires Tensorboard"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return unittest.skipUnless(is_wandb_available()		,       "test requires wandb"    )(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					Tuple    ):



    '''simple docstring'''





    return unittest.skipUnless(is_comet_ml_available()		,       "test requires comet_ml"    )(SCREAMING_SNAKE_CASE_    )


_SCREAMING_SNAKE_CASE	 =							(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def 	__a(SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return unittest.skipUnless(
        _atleast_one_tracker_available		,       "test requires at least one tracker to be available and for `comet_ml` to not be installed"		,       )(SCREAMING_SNAKE_CASE_    )

class    lowerCAmelCase_		(		unittest.TestCase		):
 __lowerCamelCase						:							Union[str, Any]         =					True




 @classmethod
 def 							_snake_case   (	cls		)    ->							Tuple:
     _lowerCAmelCase				=      tempfile.mkdtemp()




 @classmethod
 def 							_snake_case   (	cls		)    ->							List[Any]:
     if os.path.exists(cls.tmpdir		):
         shutil.rmtree(cls.tmpdir		)





 def 							_snake_case   (	self		)    ->							Optional[int]:
     if self.clear_on_setup:
         for path in Path(self.tmpdir		).glob("**/*"		):
             if path.is_file():
                 path.unlink()
             elif path.is_dir():
                 shutil.rmtree(_lowerCAmelCase		)







class    lowerCAmelCase_		(		unittest.TestCase		):




 def 							_snake_case   (	self		)    ->							Dict:
     super().tearDown()
     # Reset the state of the AcceleratorState singleton.
     AcceleratorState._reset_state()
     PartialState._reset_state()







class    lowerCAmelCase_		(		unittest.TestCase		):




 def 							_snake_case   (	self			,     _lowerCAmelCase		)    ->							List[Any]:
     _lowerCAmelCase				=      mocks if isinstance(_lowerCAmelCase			,     (tuple, list)		) else [mocks]
     for m in self.mocks:
         m.start()
         self.addCleanup(m.stop		)







def 	__a(SCREAMING_SNAKE_CASE_  :					Optional[Any]    ):



    '''simple docstring'''





    _lowerCAmelCase				=      AcceleratorState()
    _lowerCAmelCase				=      tensor[None].clone().to(state.device    )
    _lowerCAmelCase				=      gather(SCREAMING_SNAKE_CASE_    ).cpu()
    _lowerCAmelCase				=      tensor[0].cpu()
    for i in range(tensors.shape[0]    ):
        if not torch.equal(tensors[i]		,       SCREAMING_SNAKE_CASE_    ):
            return False
    return True

class    lowerCAmelCase_		:




 def __init__(	self			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							Tuple:
     _lowerCAmelCase				=      returncode
     _lowerCAmelCase				=      stdout
     _lowerCAmelCase				=      stderr







async def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					List[Any]    ):



    '''simple docstring'''





    while True:
        _lowerCAmelCase				=      await stream.readline()
        if line:
            callback(SCREAMING_SNAKE_CASE_    )
        else:
            break


async def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					int=None		,       SCREAMING_SNAKE_CASE_  :					Optional[int]=None		,       SCREAMING_SNAKE_CASE_  :					List[str]=None		,       SCREAMING_SNAKE_CASE_  :					List[Any]=False		,       SCREAMING_SNAKE_CASE_  :					Optional[int]=False    ):



    '''simple docstring'''





    if echo:
        print("\nRunning: "		,       " ".join(SCREAMING_SNAKE_CASE_    )    )

    _lowerCAmelCase				=      await asyncio.create_subprocess_exec(
        cmd[0]		,       *cmd[1:]		,       stdin=SCREAMING_SNAKE_CASE_		,       stdout=asyncio.subprocess.PIPE		,       stderr=asyncio.subprocess.PIPE		,       env=SCREAMING_SNAKE_CASE_		,       )

    # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
    # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
    #
    # If it starts hanging, will need to switch to the following code. The problem is that no data
    # will be seen until it's done and if it hangs for example there will be no debug info.
    # out, err = await p.communicate()
    # return _RunOutput(p.returncode, out, err)

    _lowerCAmelCase				=      []
    _lowerCAmelCase				=      []

    def tee(SCREAMING_SNAKE_CASE_  :					Union[str, Any]		,       SCREAMING_SNAKE_CASE_  :					int		,       SCREAMING_SNAKE_CASE_  :					Optional[Any]		,       SCREAMING_SNAKE_CASE_  :					Optional[int]=""    ):
        _lowerCAmelCase				=      line.decode("utf-8"    ).rstrip()
        sink.append(SCREAMING_SNAKE_CASE_    )
        if not quiet:
            print(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       file=SCREAMING_SNAKE_CASE_    )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            asyncio.create_task(_read_stream(p.stdout		,       lambda SCREAMING_SNAKE_CASE_    : tee(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       sys.stdout		,       label="stdout:"    )    )    ),
            asyncio.create_task(_read_stream(p.stderr		,       lambda SCREAMING_SNAKE_CASE_    : tee(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       sys.stderr		,       label="stderr:"    )    )    ),
        ]		,       timeout=SCREAMING_SNAKE_CASE_		,       )
    return _RunOutput(await p.wait()		,       SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]		,       SCREAMING_SNAKE_CASE_  :					List[Any]=None		,       SCREAMING_SNAKE_CASE_  :					Dict=None		,       SCREAMING_SNAKE_CASE_  :					int=180		,       SCREAMING_SNAKE_CASE_  :					Optional[int]=False		,       SCREAMING_SNAKE_CASE_  :					Tuple=True    ):



    '''simple docstring'''





    _lowerCAmelCase				=      asyncio.get_event_loop()
    _lowerCAmelCase				=      loop.run_until_complete(
        _stream_subprocess(SCREAMING_SNAKE_CASE_		,       env=SCREAMING_SNAKE_CASE_		,       stdin=SCREAMING_SNAKE_CASE_		,       timeout=SCREAMING_SNAKE_CASE_		,       quiet=SCREAMING_SNAKE_CASE_		,       echo=SCREAMING_SNAKE_CASE_    )    )

    _lowerCAmelCase				=      " ".join(SCREAMING_SNAKE_CASE_    )
    if result.returncode > 0:
        _lowerCAmelCase				=      "\n".join(result.stderr    )
        raise RuntimeError(
            F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
            F'''The combined stderr from workers follows:\n{stderr}'''    )

    return result

class    lowerCAmelCase_		(		__magic_name__		):
 pass







def 	__a(SCREAMING_SNAKE_CASE_  :					List[str]		,       SCREAMING_SNAKE_CASE_  :					Union[str, Any]=False    ):



    '''simple docstring'''





    try:
        _lowerCAmelCase				=      subprocess.check_output(SCREAMING_SNAKE_CASE_		,       stderr=subprocess.STDOUT    )
        if return_stdout:
            if hasattr(SCREAMING_SNAKE_CASE_		,       "decode"    ):
                _lowerCAmelCase				=      output.decode("utf-8"    )
            return output
    except subprocess.CalledProcessError as e:
        raise SubprocessCallException(
            F'''Command `{' '.join(SCREAMING_SNAKE_CASE_    )}` failed with the following error:\n\n{e.output.decode()}'''    ) from e









'''simple docstring'''


import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
_SCREAMING_SNAKE_CASE	 =							"src/transformers"
_SCREAMING_SNAKE_CASE	 =							"docs/source/en"
_SCREAMING_SNAKE_CASE	 =							"."


def 	__a(SCREAMING_SNAKE_CASE_  :					int		,       SCREAMING_SNAKE_CASE_  :					Tuple		,       SCREAMING_SNAKE_CASE_  :					Union[str, Any]    ):



    '''simple docstring'''





    with open(SCREAMING_SNAKE_CASE_		,       "r"		,       encoding="utf-8"		,       newline="\n"    ) as f:
        _lowerCAmelCase				=      f.readlines()
    # Find the start prompt.
    _lowerCAmelCase				=      0
    while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_    ):
        start_index += 1
    start_index += 1

    _lowerCAmelCase				=      start_index
    while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_    ):
        end_index += 1
    end_index -= 1

    while len(lines[start_index]    ) <= 1:
        start_index += 1
    while len(lines[end_index]    ) <= 1:
        end_index -= 1
    end_index += 1
    return "".join(lines[start_index:end_index]    ), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
_SCREAMING_SNAKE_CASE	 =							"Model|Encoder|Decoder|ForConditionalGeneration"
# Regexes that match TF/Flax/PT model names.
_SCREAMING_SNAKE_CASE	 =							re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
_SCREAMING_SNAKE_CASE	 =							re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
_SCREAMING_SNAKE_CASE	 =							re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")


# This is to make sure the transformers module imported is the one in the repo.
_SCREAMING_SNAKE_CASE	 =							direct_transformers_import(TRANSFORMERS_PATH)


def 	__a(SCREAMING_SNAKE_CASE_  :					Union[str, Any]    ):



    '''simple docstring'''





    _lowerCAmelCase				=      re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)"		,       SCREAMING_SNAKE_CASE_    )
    return [m.group(0    ) for m in matches]


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					int    ):



    '''simple docstring'''





    _lowerCAmelCase				=      2 if text == "✅" or text == "❌" else len(SCREAMING_SNAKE_CASE_    )
    _lowerCAmelCase				=      (width - text_length) // 2
    _lowerCAmelCase				=      width - text_length - left_indent
    return " " * left_indent + text + " " * right_indent


def 	__a():



    '''simple docstring'''





    _lowerCAmelCase				=      transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
    _lowerCAmelCase				=      {
        name: config_maping_names[code]
        for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
        if code in config_maping_names
    }
    _lowerCAmelCase				=      {name: config.replace("Config"		,       ""    ) for name, config in model_name_to_config.items()}

    # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
    _lowerCAmelCase				=      collections.defaultdict(SCREAMING_SNAKE_CASE_    )
    _lowerCAmelCase				=      collections.defaultdict(SCREAMING_SNAKE_CASE_    )
    _lowerCAmelCase				=      collections.defaultdict(SCREAMING_SNAKE_CASE_    )
    _lowerCAmelCase				=      collections.defaultdict(SCREAMING_SNAKE_CASE_    )
    _lowerCAmelCase				=      collections.defaultdict(SCREAMING_SNAKE_CASE_    )

    # Let's lookup through all transformers object (once).
    for attr_name in dir(SCREAMING_SNAKE_CASE_    ):
        _lowerCAmelCase				=      None
        if attr_name.endswith("Tokenizer"    ):
            _lowerCAmelCase				=      slow_tokenizers
            _lowerCAmelCase				=      attr_name[:-9]
        elif attr_name.endswith("TokenizerFast"    ):
            _lowerCAmelCase				=      fast_tokenizers
            _lowerCAmelCase				=      attr_name[:-13]
        elif _re_tf_models.match(SCREAMING_SNAKE_CASE_    ) is not None:
            _lowerCAmelCase				=      tf_models
            _lowerCAmelCase				=      _re_tf_models.match(SCREAMING_SNAKE_CASE_    ).groups()[0]
        elif _re_flax_models.match(SCREAMING_SNAKE_CASE_    ) is not None:
            _lowerCAmelCase				=      flax_models
            _lowerCAmelCase				=      _re_flax_models.match(SCREAMING_SNAKE_CASE_    ).groups()[0]
        elif _re_pt_models.match(SCREAMING_SNAKE_CASE_    ) is not None:
            _lowerCAmelCase				=      pt_models
            _lowerCAmelCase				=      _re_pt_models.match(SCREAMING_SNAKE_CASE_    ).groups()[0]

        if lookup_dict is not None:
            while len(SCREAMING_SNAKE_CASE_    ) > 0:
                if attr_name in model_name_to_prefix.values():
                    _lowerCAmelCase				=      True
                    break
                # Try again after removing the last word in the name
                _lowerCAmelCase				=      "".join(camel_case_split(SCREAMING_SNAKE_CASE_    )[:-1]    )

    # Let's build that table!
    _lowerCAmelCase				=      list(model_name_to_config.keys()    )
    model_names.sort(key=str.lower    )
    _lowerCAmelCase				=      ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"]
    # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
    _lowerCAmelCase				=      [len(SCREAMING_SNAKE_CASE_    ) + 2 for c in columns]
    _lowerCAmelCase				=      max([len(SCREAMING_SNAKE_CASE_    ) for name in model_names]    ) + 2

    # Build the table per se
    _lowerCAmelCase				=      "|" + "|".join([_center_text(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    ) for c, w in zip(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    )]    ) + "|\n"
    # Use ":-----:" format to center-aligned table cell texts
    table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths]    ) + "|\n"

    _lowerCAmelCase				=      {True: "✅", False: "❌"}
    for name in model_names:
        _lowerCAmelCase				=      model_name_to_prefix[name]
        _lowerCAmelCase				=      [
            name,
            check[slow_tokenizers[prefix]],
            check[fast_tokenizers[prefix]],
            check[pt_models[prefix]],
            check[tf_models[prefix]],
            check[flax_models[prefix]],
        ]
        table += "|" + "|".join([_center_text(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    ) for l, w in zip(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    )]    ) + "|\n"
    return table


def 	__a(SCREAMING_SNAKE_CASE_  :					Union[str, Any]=False    ):



    '''simple docstring'''





    _lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase				=      _find_text_in_file(
        filename=os.path.join(SCREAMING_SNAKE_CASE_		,       "index.md"    )		,       start_prompt="<!--This table is updated automatically from the auto modules"		,       end_prompt="<!-- End table-->"		,       )
    _lowerCAmelCase				=      get_model_table_from_auto_modules()

    if current_table != new_table:
        if overwrite:
            with open(os.path.join(SCREAMING_SNAKE_CASE_		,       "index.md"    )		,       "w"		,       encoding="utf-8"		,       newline="\n"    ) as f:
                f.writelines(lines[:start_index] + [new_table] + lines[end_index:]    )
        else:
            raise ValueError(
                "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this."    )


if __name__ == "__main__":
       _SCREAMING_SNAKE_CASE	 =							argparse.ArgumentParser()
       parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
       _SCREAMING_SNAKE_CASE	 =							parser.parse_args()

       check_model_table(args.fix_and_overwrite)


