


'''simple docstring'''







# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


lowerCAmelCase     :  int											=    Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

lowerCAmelCase     :  List[Any]											=    {"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCAmelCase     :  str											=    """zero2"""
lowerCAmelCase     :  int											=    """zero3"""
lowerCAmelCase     :  List[str]											=    [ZEROa, ZEROa]






def       lowercase					(_A ,    _A ,    _A       ):







       """simple docstring"""







       _lowerCAmelCase     :				List[Any]       =							parameterized.to_safe_name('_'.join(str(_A       ) for x in param.args       )       )
       return f'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
lowerCAmelCase     :  List[str]											=    list(itertools.product(stages, models.keys()))
@slow
@require_deepspeed
@require_torch_gpu
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     @parameterized.expand(snake_case__   ,						name_func=snake_case__ )
     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            self.run_and_check(
                stage=snake_case__   ,						model=snake_case__   ,						distributed=snake_case__   ,						fpaa=snake_case__   ,						)







     @require_torch_multi_gpu
     @parameterized.expand(snake_case__   ,						name_func=snake_case__ )
     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            self.run_and_check(
                stage=snake_case__   ,						model=snake_case__   ,						distributed=snake_case__   ,						fpaa=snake_case__   ,						)







     @parameterized.expand(snake_case__   ,						name_func=snake_case__ )
     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            self.run_and_check(
                stage=snake_case__   ,						model=snake_case__   ,						distributed=snake_case__   ,						fpaa=snake_case__   ,						)







     @require_torch_multi_gpu
     @parameterized.expand(snake_case__   ,						name_func=snake_case__ )
     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            self.run_and_check(
                stage=snake_case__   ,						model=snake_case__   ,						distributed=snake_case__   ,						fpaa=snake_case__   ,						)







     def a						(			self   ,						snake_case__ ):

            '''simple docstring'''

            pass







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__ = 10   ,						snake_case__ = True   ,						snake_case__ = True   ,						snake_case__ = True   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							models[model]

            _lowerCAmelCase     :				List[Any]       =							self.run_trainer(
                stage=snake_case__   ,						model_name=snake_case__   ,						eval_steps=snake_case__   ,						num_train_epochs=1   ,						distributed=snake_case__   ,						fpaa=snake_case__   ,						)

            self.do_checks(snake_case__ )

            return output_dir







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__ = 10   ,						snake_case__ = 1   ,						snake_case__ = True   ,						snake_case__ = True   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.get_auto_remove_tmp_dir('./xxx'   ,						after=snake_case__ )
            _lowerCAmelCase     :				Optional[int]       =							F'\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(snake_case__ )}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        '.split()

            if fpaa:
                   args.extend(['--fp16'] )

            # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
            # hence the separate config files
            _lowerCAmelCase     :				Dict       =							F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
            _lowerCAmelCase     :				Union[str, Any]       =							[F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
            _lowerCAmelCase     :				Optional[Any]       =							self.get_launcher(snake_case__ )

            _lowerCAmelCase     :				Any       =							launcher + script + args + ds_args
            # keep for quick debug
            # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
            execute_subprocess_async(snake_case__   ,						env=self.get_env() )

            return output_dir







     def a						(			self   ,						snake_case__=False ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[Any]       =							min(2   ,						get_gpu_count() ) if distributed else 1
            return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()





'''simple docstring'''







import argparse
from collections import defaultdict

import yaml


lowerCAmelCase     :  Dict											=    """docs/source/en/_toctree.yml"""






def       lowercase					(_A       ):







       """simple docstring"""







       _lowerCAmelCase     :				Optional[int]       =							defaultdict(_A       )
       _lowerCAmelCase     :				Tuple       =							[]
       _lowerCAmelCase     :				Dict       =							[]
       for doc in doc_list:
              if "local" in doc:
                     counts[doc["local"]] += 1

              if doc["title"].lower() == "overview":
                     overview_doc.append({'local': doc['local'], 'title': doc['title']}       )
              else:
                     new_doc_list.append(_A       )

       _lowerCAmelCase     :				str       =							new_doc_list
       _lowerCAmelCase     :				List[Any]       =							[key for key, value in counts.items() if value > 1]

       _lowerCAmelCase     :				List[str]       =							[]
       for duplicate_key in duplicates:
              _lowerCAmelCase     :				Any       =							list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key}       )
              if len(_A       ) > 1:
                     raise ValueError(
                         f'{duplicate_key} is present several times in the documentation table of content at '
                         '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
                         'others.'       )
              # Only add this once
              new_doc.append({'local': duplicate_key, 'title': titles[0]}       )

       # Add none duplicate-keys
       new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1]       )
       _lowerCAmelCase     :				Any       =							sorted(_A ,    key=lambda _A       : s["title"].lower()       )

       # "overview" gets special treatment and is always first
       if len(_A       ) > 1:
              raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.'       )

       overview_doc.extend(_A       )

       # Sort
       return overview_doc






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Union[str, Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Tuple       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				str       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Dict       =							0
       while api_doc[scheduler_idx]["title"] != "Schedulers":
              scheduler_idx += 1

       _lowerCAmelCase     :				Optional[int]       =							api_doc[scheduler_idx]['sections']
       _lowerCAmelCase     :				Any       =							clean_doc_toc(_A       )

       _lowerCAmelCase     :				int       =							False
       if new_scheduler_doc != scheduler_doc:
              _lowerCAmelCase     :				str       =							True
              if overwrite:
                     _lowerCAmelCase     :				int       =							new_scheduler_doc

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				Dict       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Optional[Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Optional[Any]       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				Union[str, Any]       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Optional[int]       =							0
       while api_doc[pipeline_idx]["title"] != "Pipelines":
              pipeline_idx += 1

       _lowerCAmelCase     :				List[Any]       =							False
       _lowerCAmelCase     :				List[Any]       =							api_doc[pipeline_idx]['sections']
       _lowerCAmelCase     :				Union[str, Any]       =							[]

       # sort sub pipeline docs
       for pipeline_doc in pipeline_docs:
              if "section" in pipeline_doc:
                     _lowerCAmelCase     :				Tuple       =							pipeline_doc['section']
                     _lowerCAmelCase     :				Optional[int]       =							clean_doc_toc(_A       )
                     if overwrite:
                            _lowerCAmelCase     :				str       =							new_sub_pipeline_doc
              new_pipeline_docs.append(_A       )

       # sort overall pipeline doc
       _lowerCAmelCase     :				str       =							clean_doc_toc(_A       )

       if new_pipeline_docs != pipeline_docs:
              _lowerCAmelCase     :				Any       =							True
              if overwrite:
                     _lowerCAmelCase     :				Optional[int]       =							new_pipeline_docs

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				str       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )


if __name__ == "__main__":
       lowerCAmelCase     :  Tuple											=    argparse.ArgumentParser()
       parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
       lowerCAmelCase     :  List[Any]											=    parser.parse_args()

       check_scheduler_doc(args.fix_and_overwrite)
       check_pipeline_doc(args.fix_and_overwrite)

