

import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     str   ,      SCREAMING_SNAKE_CASE__      :     Dict   ,      SCREAMING_SNAKE_CASE__      :     Union[str, Any]   ,      SCREAMING_SNAKE_CASE__      :     List[str]   ,      SCREAMING_SNAKE_CASE__      :     Any=True   ,      SCREAMING_SNAKE_CASE__      :     Dict="pt"				)							->				Any:





    '''simple docstring'''






    A__   				=       {'add_prefix_space': True} if isinstance(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				) and not line.startswith(' '				) else {}
    A__   				=       padding_side
    return tokenizer(
        [line]   ,      max_length=SCREAMING_SNAKE_CASE__   ,      padding='max_length' if pad_to_max_length else None   ,      truncation=SCREAMING_SNAKE_CASE__   ,      return_tensors=SCREAMING_SNAKE_CASE__   ,      add_special_tokens=SCREAMING_SNAKE_CASE__   ,      **SCREAMING_SNAKE_CASE__   ,      )
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     Tuple   ,      SCREAMING_SNAKE_CASE__      :     List[Any]=None   ,      )							->				Optional[int]:





    '''simple docstring'''






    A__   				=       input_ids.ne(SCREAMING_SNAKE_CASE__				).any(dim=0				)
    if attention_mask is None:
        return input_ids[:, keep_column_mask]
    else:
        return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])


class 			A						(							_UpperCAmelCase			):







    """simple docstring"""





    def __init__(				self			:	str,lowercase_			:	List[str],lowercase_			:	Union[str, Any],lowercase_			:	Any,lowercase_			:	List[Any],lowercase_			:	int="train",lowercase_			:	Any=None,lowercase_			:	int=None,lowercase_			:	Optional[int]=None,lowercase_			:	List[Any]="",)->   List[str]:





        '''simple docstring'''







        super().__init__()
        A__   				=       Path(lowercase_		).joinpath(type_path + '.source'		)
        A__   				=       Path(lowercase_		).joinpath(type_path + '.target'		)
        A__   				=       self.get_char_lens(self.src_file		)
        A__   				=       max_source_length
        A__   				=       max_target_length
        assert min(self.src_lens		) > 0, F'found empty line in {self.src_file}'
        A__   				=       tokenizer
        A__   				=       prefix
        if n_obs is not None:
            A__   				=       self.src_lens[:n_obs]
        A__   				=       src_lang
        A__   				=       tgt_lang


    def __len__(				self			:	List[str]		)->   List[Any]:





        '''simple docstring'''







        return len(self.src_lens		)


    def __getitem__(				self			:	Optional[Any],lowercase_			:	str		)->   Dict[str, torch.Tensor]:





        '''simple docstring'''







        A__   				=       index + 1  # linecache starts at 1
        A__   				=       self.prefix + linecache.getline(str(self.src_file		),lowercase_		).rstrip('\n'		)
        A__   				=       linecache.getline(str(self.tgt_file		),lowercase_		).rstrip('\n'		)
        assert source_line, F'empty source line for index {index}'
        assert tgt_line, F'empty tgt line for index {index}'

        # Need to add eos token manually for T5
        if isinstance(self.tokenizer,lowercase_		):
            source_line += self.tokenizer.eos_token
            tgt_line += self.tokenizer.eos_token

        # Pad source and target to the right
        A__   				=       (
            self.tokenizer.question_encoder if isinstance(self.tokenizer,lowercase_		) else self.tokenizer
        )
        A__   				=       self.tokenizer.generator if isinstance(self.tokenizer,lowercase_		) else self.tokenizer

        A__   				=       encode_line(lowercase_,lowercase_,self.max_source_length,'right'		)
        A__   				=       encode_line(lowercase_,lowercase_,self.max_target_length,'right'		)

        A__   				=       source_inputs['input_ids'].squeeze()
        A__   				=       target_inputs['input_ids'].squeeze()
        A__   				=       source_inputs['attention_mask'].squeeze()
        return {
            "input_ids": source_ids,
            "attention_mask": src_mask,
            "decoder_input_ids": target_ids,
        }


    @staticmethod
    def 						snake_case__					(				lowercase_			:	List[str]		)->   str:





        '''simple docstring'''







        return [len(lowercase_		) for x in Path(lowercase_		).open().readlines()]


    def 						snake_case__					(				self			:	Dict,lowercase_			:	Union[str, Any]		)->   Dict[str, torch.Tensor]:





        '''simple docstring'''







        A__   				=       torch.stack([x['input_ids'] for x in batch]		)
        A__   				=       torch.stack([x['attention_mask'] for x in batch]		)
        A__   				=       torch.stack([x['decoder_input_ids'] for x in batch]		)
        A__   				=       (
            self.tokenizer.generator.pad_token_id
            if isinstance(self.tokenizer,lowercase_		)
            else self.tokenizer.pad_token_id
        )
        A__   				=       (
            self.tokenizer.question_encoder.pad_token_id
            if isinstance(self.tokenizer,lowercase_		)
            else self.tokenizer.pad_token_id
        )
        A__   				=       trim_batch(lowercase_,lowercase_		)
        A__				,						A__   				=       trim_batch(lowercase_,lowercase_,attention_mask=lowercase_		)
        A__   				=       {
            'input_ids': source_ids,
            'attention_mask': source_mask,
            'decoder_input_ids': y,
        }
        return batch




lowercase_			=  getLogger(__name__)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     List[List]				)							->				Optional[int]:





    '''simple docstring'''






    return list(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__				)				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     str				)							->				None:





    '''simple docstring'''






    A__   				=       get_git_info()
    save_json(SCREAMING_SNAKE_CASE__   ,      os.path.join(SCREAMING_SNAKE_CASE__   ,      'git_log.json'				)				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     Optional[Any]   ,      SCREAMING_SNAKE_CASE__      :     str=4   ,      **SCREAMING_SNAKE_CASE__      :     Union[str, Any]				)							->				str:





    '''simple docstring'''






    with open(SCREAMING_SNAKE_CASE__   ,      'w'				) as f:
        json.dump(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__   ,      indent=SCREAMING_SNAKE_CASE__   ,      **SCREAMING_SNAKE_CASE__				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Any				)							->				Dict:





    '''simple docstring'''






    with open(SCREAMING_SNAKE_CASE__				) as f:
        return json.load(SCREAMING_SNAKE_CASE__				)
def 						_snake_case(   )							->				List[Any]:





    '''simple docstring'''






    A__   				=       git.Repo(search_parent_directories=SCREAMING_SNAKE_CASE__				)
    A__   				=       {
        'repo_id': str(SCREAMING_SNAKE_CASE__				),
        'repo_sha': str(repo.head.object.hexsha				),
        'repo_branch': str(repo.active_branch				),
        'hostname': str(socket.gethostname()				),
    }
    return repo_infos
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Callable   ,      SCREAMING_SNAKE_CASE__      :     Iterable				)							->				List:





    '''simple docstring'''






    return list(map(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Optional[int]   ,      SCREAMING_SNAKE_CASE__      :     List[str]				)							->				Dict:





    '''simple docstring'''






    with open(SCREAMING_SNAKE_CASE__   ,      'wb'				) as f:
        return pickle.dump(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Optional[Any]				)							->				Any:





    '''simple docstring'''






    def remove_articles(SCREAMING_SNAKE_CASE__      :     Any				):
        return re.sub(R'\b(a|an|the)\b'   ,      ' '   ,      SCREAMING_SNAKE_CASE__				)

    def white_space_fix(SCREAMING_SNAKE_CASE__      :     str				):
        return " ".join(text.split()				)

    def remove_punc(SCREAMING_SNAKE_CASE__      :     List[str]				):
        A__   				=       set(string.punctuation				)
        return "".join(ch for ch in text if ch not in exclude				)

    def lower(SCREAMING_SNAKE_CASE__      :     Tuple				):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE__				)				)				)				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Union[str, Any]   ,      SCREAMING_SNAKE_CASE__      :     List[Any]				)							->				Union[str, Any]:





    '''simple docstring'''






    A__   				=       normalize_answer(SCREAMING_SNAKE_CASE__				).split()
    A__   				=       normalize_answer(SCREAMING_SNAKE_CASE__				).split()
    A__   				=       Counter(SCREAMING_SNAKE_CASE__				) & Counter(SCREAMING_SNAKE_CASE__				)
    A__   				=       sum(common.values()				)
    if num_same == 0:
        return 0
    A__   				=       1.0 * num_same / len(SCREAMING_SNAKE_CASE__				)
    A__   				=       1.0 * num_same / len(SCREAMING_SNAKE_CASE__				)
    A__   				=       (2 * precision * recall) / (precision + recall)
    return fa
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     str   ,      SCREAMING_SNAKE_CASE__      :     Dict				)							->				Union[str, Any]:





    '''simple docstring'''






    return normalize_answer(SCREAMING_SNAKE_CASE__				) == normalize_answer(SCREAMING_SNAKE_CASE__				)
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     List[str]   ,      SCREAMING_SNAKE_CASE__      :     List[str]				)							->				Dict:





    '''simple docstring'''






    assert len(SCREAMING_SNAKE_CASE__				) == len(SCREAMING_SNAKE_CASE__				)
    A__   				=       0
    for hypo, pred in zip(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				):
        em += exact_match_score(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
    if len(SCREAMING_SNAKE_CASE__				) > 0:
        em /= len(SCREAMING_SNAKE_CASE__				)
    return {"em": em}
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Union[str, Any]				)							->				Tuple:





    '''simple docstring'''






    return model_prefix.startswith('rag'				)

def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     List[Any]   ,      SCREAMING_SNAKE_CASE__      :     str   ,      SCREAMING_SNAKE_CASE__      :     Tuple				)							->				List[Any]:





    '''simple docstring'''






    A__   				=       {p: p for p in extra_params}
    # T5 models don't have `dropout` param, they have `dropout_rate` instead
    A__   				=       'dropout_rate'
    for p in extra_params:
        if getattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				):
            if not hasattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				) and not hasattr(SCREAMING_SNAKE_CASE__   ,      equivalent_param[p]				):
                logger.info('config doesn\'t have a `{}` attribute'.format(SCREAMING_SNAKE_CASE__				)				)
                delattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
                continue
            A__   				=       p if hasattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				) else equivalent_param[p]
            setattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__   ,      getattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)				)
            delattr(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
    return hparams, config




# 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


lowercase_			=  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)

lowercase_			=  {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"}

lowercase_			=  "zero2"
lowercase_			=  "zero3"
lowercase_			=  [ZEROa, ZEROa]
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Optional[int]   ,      SCREAMING_SNAKE_CASE__      :     Tuple   ,      SCREAMING_SNAKE_CASE__      :     List[Any]				)							->				Dict:





    '''simple docstring'''






    A__   				=       parameterized.to_safe_name('_'.join(str(SCREAMING_SNAKE_CASE__				) for x in param.args				)				)
    return f'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
lowercase_			=  list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class 			A						(							_UpperCAmelCase			):







    """simple docstring"""





    @parameterized.expand(lowercase_,name_func=lowercase_		)
    def 						snake_case__					(				self			:	int,lowercase_			:	str,lowercase_			:	Any		)->   Optional[int]:





        '''simple docstring'''







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


    @require_torch_multi_gpu
    @parameterized.expand(lowercase_,name_func=lowercase_		)
    def 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	Optional[Any],lowercase_			:	List[Any]		)->   int:





        '''simple docstring'''







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


    @parameterized.expand(lowercase_,name_func=lowercase_		)
    def 						snake_case__					(				self			:	List[str],lowercase_			:	List[str],lowercase_			:	List[Any]		)->   Any:





        '''simple docstring'''







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


    @require_torch_multi_gpu
    @parameterized.expand(lowercase_,name_func=lowercase_		)
    def 						snake_case__					(				self			:	Dict,lowercase_			:	Optional[Any],lowercase_			:	List[Any]		)->   Optional[int]:





        '''simple docstring'''







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


    def 						snake_case__					(				self			:	Tuple,lowercase_			:	Any		)->   Union[str, Any]:





        '''simple docstring'''







        pass


    def 						snake_case__					(				self			:	int,lowercase_			:	str,lowercase_			:	str,lowercase_			:	int = 1_0,lowercase_			:	bool = True,lowercase_			:	bool = True,lowercase_			:	bool = True,)->   Union[str, Any]:





        '''simple docstring'''







        A__   				=       models[model]

        A__   				=       self.run_trainer(
            stage=lowercase_,model_name=lowercase_,eval_steps=lowercase_,num_train_epochs=1,distributed=lowercase_,fpaa=lowercase_,)

        self.do_checks(lowercase_		)

        return output_dir


    def 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	str,lowercase_			:	str,lowercase_			:	int = 1_0,lowercase_			:	int = 1,lowercase_			:	bool = True,lowercase_			:	bool = True,)->   Any:





        '''simple docstring'''







        A__   				=       self.get_auto_remove_tmp_dir('./xxx',after=lowercase_		)
        A__   				=       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(lowercase_		)}\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
        A__   				=       F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
        A__   				=       [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
        A__   				=       self.get_launcher(lowercase_		)

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

        return output_dir


    def 						snake_case__					(				self			:	Any,lowercase_			:	int=False		)->   Tuple:





        '''simple docstring'''







        A__   				=       min(2,get_gpu_count()		) if distributed else 1
        return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()

