


import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


UpperCamelCase								=	logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""")


def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE = 16_000       ):
  A_      :				Any		     =					int(round(sample_rate * max_length       )       )
  if len(SCREAMING_SNAKE_CASE       ) <= sample_length:
    return wav
  A_      :				Tuple		     =					randint(0 ,			len(SCREAMING_SNAKE_CASE       ) - sample_length - 1       )
  return wav[random_offset : random_offset + sample_length]






@dataclass
class   _lowerCamelCase :




       """simple docstring"""
       snake_case      =    field(default=UpperCamelCase					,							metadata={"help": "Name of a dataset from the datasets package"}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "A file containing the training audio paths and labels."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "A file containing the validation audio paths and labels."}			)
       snake_case      =    field(
           default="train"					,							metadata={
               "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
           }					,							)
       snake_case      =    field(
           default="validation"					,							metadata={
               "help": (
                   "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
               )
           }					,							)
       snake_case      =    field(
           default="audio"					,							metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}					,							)
       snake_case      =    field(
           default="label"					,							metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={
               "help": (
                   "For debugging purposes or quicker training, truncate the number of training examples to this "
                   "value if set."
               )
           }					,							)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={
               "help": (
                   "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                   "value if set."
               )
           }					,							)
       snake_case      =    field(
           default=20					,							metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}					,							)






@dataclass
class   _lowerCamelCase :




       """simple docstring"""
       snake_case      =    field(
           default="facebook/wav2vec2-base"					,							metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}					,							)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}			)
       snake_case      =    field(
           default="main"					,							metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}					,							)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Name or path of preprocessor config."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Whether to freeze the feature encoder layers of the model."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Whether to generate an attention mask in the feature extractor."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={
               "help": (
                   "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
                   "with private models)."
               )
           }					,							)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Whether to freeze the feature extractor layers of the model."}			)
       snake_case      =    field(
           default=UpperCamelCase					,							metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}					,							)



       def        _snake_case       (      self		)->Optional[Any]:




         '''simple docstring'''





         if not self.freeze_feature_extractor and self.freeze_feature_encoder:
           warnings.warn(
               '''The argument `--freeze_feature_extractor` is deprecated and '''
               '''will be removed in a future version. Use `--freeze_feature_encoder`'''
               '''instead. Setting `freeze_feature_encoder==True`.'''				,       _SCREAMING_SNAKE_CASE				,       )
         if self.freeze_feature_extractor and not self.freeze_feature_encoder:
           raise ValueError(
               '''The argument `--freeze_feature_extractor` is deprecated and '''
               '''should not be used in combination with `--freeze_feature_encoder`.'''
               '''Only make use of `--freeze_feature_encoder`.'''		)




def   _SCREAMING_SNAKE_CASE	( ):
  # See all possible arguments in src/transformers/training_args.py
  # or by passing the --help flag to this script.
  # We now keep distinct sets of args, for a cleaner separation of concerns.

  A_      :				List[str]		     =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
  if len(sys.argv       ) == 2 and sys.argv[1].endswith('''.json'''       ):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    A_     ,       A_     ,       A_      :				Tuple		     =					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
  else:
    A_     ,       A_     ,       A_      :				Optional[int]		     =					parser.parse_args_into_dataclasses()

  # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
  # information sent is the one passed as arguments along with your Python/PyTorch versions.
  send_example_telemetry('''run_audio_classification''' ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )

  # Setup logging
  logging.basicConfig(
      format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,			datefmt='''%m/%d/%Y %H:%M:%S''' ,			handlers=[logging.StreamHandler(sys.stdout       )] ,			)

  if training_args.should_log:
    # The default of training_args.log_level is passive, so we set log level at info here to have that default.
    transformers.utils.logging.set_verbosity_info()

  A_      :				Any		     =					training_args.get_process_log_level()
  logger.setLevel(SCREAMING_SNAKE_CASE       )
  transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE       )
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()

  # Log on each process the small summary:
  logger.warning(
      f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} '''
      + f'''distributed training: {bool(training_args.local_rank != -1       )}, 16-bits training: {training_args.fpaa}'''       )
  logger.info(f'''Training/evaluation parameters {training_args}'''       )

  # Set seed before initializing model.
  set_seed(training_args.seed       )

  # Detecting last checkpoint.
  A_      :				Any		     =					None
  if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
    A_      :				Dict		     =					get_last_checkpoint(training_args.output_dir       )
    if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
      raise ValueError(
          f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
          '''Use --overwrite_output_dir to train from scratch.'''       )
    elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
      logger.info(
          f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
          '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''       )

    # Initialize our dataset and prepare it for the audio classification task.
  A_      :				Tuple		     =					DatasetDict()
  A_      :				List[str]		     =					load_dataset(
      data_args.dataset_name ,			data_args.dataset_config_name ,			split=data_args.train_split_name ,			use_auth_token=True if model_args.use_auth_token else None ,			)
  A_      :				Dict		     =					load_dataset(
      data_args.dataset_name ,			data_args.dataset_config_name ,			split=data_args.eval_split_name ,			use_auth_token=True if model_args.use_auth_token else None ,			)

  if data_args.audio_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f'''--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. '''
        '''Make sure to set `--audio_column_name` to the correct audio column - one of '''
        f'''{", ".join(raw_datasets["train"].column_names       )}.'''       )

  if data_args.label_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f'''--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. '''
        '''Make sure to set `--label_column_name` to the correct text column - one of '''
        f'''{", ".join(raw_datasets["train"].column_names       )}.'''       )

  # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
  # transformer outputs in the classifier, but it doesn't always lead to better accuracy
  A_      :				str		     =					AutoFeatureExtractor.from_pretrained(
      model_args.feature_extractor_name or model_args.model_name_or_path ,			return_attention_mask=model_args.attention_mask ,			cache_dir=model_args.cache_dir ,			revision=model_args.model_revision ,			use_auth_token=True if model_args.use_auth_token else None ,			)

  # `datasets` takes care of automatically loading and resampling the audio,
  # so we just need to set the correct target sampling rate.
  A_      :				Optional[Any]		     =					raw_datasets.cast_column(
      data_args.audio_column_name ,			datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate       )       )

  A_      :				Dict		     =					feature_extractor.model_input_names[0]

  def train_transforms(SCREAMING_SNAKE_CASE       ):
    A_      :				Optional[Any]		     =					[]
    for audio in batch[data_args.audio_column_name]:
      A_      :				List[str]		     =					random_subsample(
          audio['''array'''] ,			max_length=data_args.max_length_seconds ,			sample_rate=feature_extractor.sampling_rate       )
      subsampled_wavs.append(SCREAMING_SNAKE_CASE       )
    A_      :				Optional[int]		     =					feature_extractor(SCREAMING_SNAKE_CASE ,			sampling_rate=feature_extractor.sampling_rate       )
    A_      :				List[str]		     =					{model_input_name: inputs.get(SCREAMING_SNAKE_CASE       )}
    A_      :				Optional[Any]		     =					list(batch[data_args.label_column_name]       )

    return output_batch

  def val_transforms(SCREAMING_SNAKE_CASE       ):
    A_      :				Optional[Any]		     =					[audio['''array'''] for audio in batch[data_args.audio_column_name]]
    A_      :				Dict		     =					feature_extractor(SCREAMING_SNAKE_CASE ,			sampling_rate=feature_extractor.sampling_rate       )
    A_      :				List[str]		     =					{model_input_name: inputs.get(SCREAMING_SNAKE_CASE       )}
    A_      :				Any		     =					list(batch[data_args.label_column_name]       )

    return output_batch

  # Prepare label mappings.
  # We'll include these in the model's config to get human readable labels in the Inference API.
  A_      :				List[Any]		     =					raw_datasets['''train'''].features[data_args.label_column_name].names
  A_     ,       A_      :				Optional[Any]		     =					{}, {}
  for i, label in enumerate(SCREAMING_SNAKE_CASE       ):
    A_      :				Union[str, Any]		     =					str(SCREAMING_SNAKE_CASE       )
    A_      :				Union[str, Any]		     =					label

  # Load the accuracy metric from the datasets package
  A_      :				Optional[Any]		     =					evaluate.load('''accuracy'''       )

  # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
  # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
  def compute_metrics(SCREAMING_SNAKE_CASE       ):
    A_      :				Union[str, Any]		     =					np.argmax(eval_pred.predictions ,			axis=1       )
    return metric.compute(predictions=SCREAMING_SNAKE_CASE ,			references=eval_pred.label_ids       )

  A_      :				Optional[int]		     =					AutoConfig.from_pretrained(
      model_args.config_name or model_args.model_name_or_path ,			num_labels=len(SCREAMING_SNAKE_CASE       ) ,			labelaid=SCREAMING_SNAKE_CASE ,			idalabel=SCREAMING_SNAKE_CASE ,			finetuning_task='''audio-classification''' ,			cache_dir=model_args.cache_dir ,			revision=model_args.model_revision ,			use_auth_token=True if model_args.use_auth_token else None ,			)
  A_      :				Tuple		     =					AutoModelForAudioClassification.from_pretrained(
      model_args.model_name_or_path ,			from_tf=bool('''.ckpt''' in model_args.model_name_or_path       ) ,			config=SCREAMING_SNAKE_CASE ,			cache_dir=model_args.cache_dir ,			revision=model_args.model_revision ,			use_auth_token=True if model_args.use_auth_token else None ,			ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,			)

  # freeze the convolutional waveform encoder
  if model_args.freeze_feature_encoder:
    model.freeze_feature_encoder()

  if training_args.do_train:
    if data_args.max_train_samples is not None:
      A_      :				List[str]		     =					(
          raw_datasets['''train'''].shuffle(seed=training_args.seed       ).select(range(data_args.max_train_samples       )       )
      )
    # Set the training transforms
    raw_datasets["train"].set_transform(SCREAMING_SNAKE_CASE ,			output_all_columns=SCREAMING_SNAKE_CASE       )

  if training_args.do_eval:
    if data_args.max_eval_samples is not None:
      A_      :				Tuple		     =					(
          raw_datasets['''eval'''].shuffle(seed=training_args.seed       ).select(range(data_args.max_eval_samples       )       )
      )
    # Set the validation transforms
    raw_datasets["eval"].set_transform(SCREAMING_SNAKE_CASE ,			output_all_columns=SCREAMING_SNAKE_CASE       )

  # Initialize our trainer
  A_      :				Any		     =					Trainer(
      model=SCREAMING_SNAKE_CASE ,			args=SCREAMING_SNAKE_CASE ,			train_dataset=raw_datasets['''train'''] if training_args.do_train else None ,			eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None ,			compute_metrics=SCREAMING_SNAKE_CASE ,			tokenizer=SCREAMING_SNAKE_CASE ,			)

  # Training
  if training_args.do_train:
    A_      :				Union[str, Any]		     =					None
    if training_args.resume_from_checkpoint is not None:
      A_      :				Tuple		     =					training_args.resume_from_checkpoint
    elif last_checkpoint is not None:
      A_      :				Tuple		     =					last_checkpoint
    A_      :				Union[str, Any]		     =					trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE       )
    trainer.save_model()
    trainer.log_metrics('''train''' ,			train_result.metrics       )
    trainer.save_metrics('''train''' ,			train_result.metrics       )
    trainer.save_state()

  # Evaluation
  if training_args.do_eval:
    A_      :				Union[str, Any]		     =					trainer.evaluate()
    trainer.log_metrics('''eval''' ,			SCREAMING_SNAKE_CASE       )
    trainer.save_metrics('''eval''' ,			SCREAMING_SNAKE_CASE       )

  # Write model card and (optionally) push to hub
  A_      :				List[Any]		     =					{
      '''finetuned_from''': model_args.model_name_or_path,
      '''tasks''': '''audio-classification''',
      '''dataset''': data_args.dataset_name,
      '''tags''': ['''audio-classification'''],
  }
  if training_args.push_to_hub:
    trainer.push_to_hub(**SCREAMING_SNAKE_CASE       )
  else:
    trainer.create_model_card(**SCREAMING_SNAKE_CASE       )


if __name__ == "__main__":
     main()








import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test






class   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       @parameterized.expand([(None,), ('''foo.json''',)]		)
       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->Tuple:




         '''simple docstring'''





         A_      :				Dict		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       bad_words_ids=[[1, 2, 3], [4, 5]]				,       )
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(_SCREAMING_SNAKE_CASE				,       config_name=_SCREAMING_SNAKE_CASE		)
           A_      :				Tuple		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE				,       config_name=_SCREAMING_SNAKE_CASE		)

         # Checks parameters that were specified
         self.assertEqual(loaded_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(loaded_config.temperature				,       0.7		)
         self.assertEqual(loaded_config.length_penalty				,       1.0		)
         self.assertEqual(loaded_config.bad_words_ids				,       [[1, 2, 3], [4, 5]]		)

         # Checks parameters that were not specified (defaults)
         self.assertEqual(loaded_config.top_k				,       50		)
         self.assertEqual(loaded_config.max_length				,       20		)
         self.assertEqual(loaded_config.max_time				,       _SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         A_      :				str		     =					AutoConfig.from_pretrained('''gpt2'''		)
         A_      :				int		     =					GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE		)
         A_      :				Dict		     =					GenerationConfig()

         # The generation config has loaded a few non-default parameters from the model config
         self.assertNotEqual(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)

         # One of those parameters is eos_token_id -- check if it matches
         self.assertNotEqual(generation_config_from_model.eos_token_id				,       default_generation_config.eos_token_id		)
         self.assertEqual(generation_config_from_model.eos_token_id				,       model_config.eos_token_id		)



       def        _snake_case       (      self		)->Optional[int]:




         '''simple docstring'''





         A_      :				List[Any]		     =					GenerationConfig()
         A_      :				Optional[Any]		     =					{
             '''max_new_tokens''': 1024,
             '''foo''': '''bar''',
         }
         A_      :				Dict		     =					copy.deepcopy(_SCREAMING_SNAKE_CASE		)
         A_      :				Optional[int]		     =					generation_config.update(**_SCREAMING_SNAKE_CASE		)

         # update_kwargs was not modified (no side effects)
         self.assertEqual(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)

         # update_kwargs was used to update the config on valid attributes
         self.assertEqual(generation_config.max_new_tokens				,       1024		)

         # `.update()` returns a dictionary of unused kwargs
         self.assertEqual(_SCREAMING_SNAKE_CASE				,       {'''foo''': '''bar'''}		)



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         A_      :				List[str]		     =					GenerationConfig()
         A_      :				int		     =					'''bar'''

         with tempfile.TemporaryDirectory('''test-generation-config'''		) as tmp_dir:
           generation_config.save_pretrained(_SCREAMING_SNAKE_CASE		)

           A_      :				Optional[Any]		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE		)
         # update_kwargs was used to update the config on valid attributes
         self.assertEqual(new_config.foo				,       '''bar'''		)

         A_      :				Optional[int]		     =					GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE		)
         assert not hasattr(_SCREAMING_SNAKE_CASE				,       '''foo'''		)  # no new kwargs should be initialized if from config







       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         A_      :				str		     =					GenerationConfig()
         self.assertEqual(default_config.temperature				,       1.0		)
         self.assertEqual(default_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(default_config.num_beams				,       1		)

         A_      :				str		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       bad_words_ids=[[1, 2, 3], [4, 5]]				,       )
         self.assertEqual(config.temperature				,       0.7		)
         self.assertEqual(config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(config.num_beams				,       1		)

         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(_SCREAMING_SNAKE_CASE		)
           A_      :				Dict		     =					GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE				,       temperature=1.0		)

         self.assertEqual(loaded_config.temperature				,       1.0		)
         self.assertEqual(loaded_config.do_sample				,       _SCREAMING_SNAKE_CASE		)
         self.assertEqual(loaded_config.num_beams				,       1		)  # default value






@is_staging_test
class   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       @classmethod
       def        _snake_case       (      cls		)->Optional[int]:




         '''simple docstring'''





         A_      :				str		     =					TOKEN
         HfFolder.save_token(_SCREAMING_SNAKE_CASE		)



       @classmethod
       def        _snake_case       (      cls		)->List[Any]:




         '''simple docstring'''





         try:
           delete_repo(token=cls._token				,       repo_id='''test-generation-config'''		)
         except HTTPError:
           pass

         try:
           delete_repo(token=cls._token				,       repo_id='''valid_org/test-generation-config-org'''		)
         except HTTPError:
           pass



       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         A_      :				List[Any]		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       )
         config.push_to_hub('''test-generation-config'''				,       use_auth_token=self._token		)

         A_      :				Optional[int]		     =					GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)

        # Reset repo
         delete_repo(token=self._token				,       repo_id='''test-generation-config'''		)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               _SCREAMING_SNAKE_CASE				,       repo_id='''test-generation-config'''				,       push_to_hub=_SCREAMING_SNAKE_CASE				,       use_auth_token=self._token		)

         A_      :				Optional[Any]		     =					GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)







       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         A_      :				Tuple		     =					GenerationConfig(
             do_sample=_SCREAMING_SNAKE_CASE				,       temperature=0.7				,       length_penalty=1.0				,       )
         config.push_to_hub('''valid_org/test-generation-config-org'''				,       use_auth_token=self._token		)

         A_      :				Union[str, Any]		     =					GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)

        # Reset repo
         delete_repo(token=self._token				,       repo_id='''valid_org/test-generation-config-org'''		)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               _SCREAMING_SNAKE_CASE				,       repo_id='''valid_org/test-generation-config-org'''				,       push_to_hub=_SCREAMING_SNAKE_CASE				,       use_auth_token=self._token		)

         A_      :				Dict		     =					GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''		)
         for k, v in config.to_dict().items():
           if k != "transformers_version":
             self.assertEqual(_SCREAMING_SNAKE_CASE				,       getattr(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)




