


import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
       from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
       lowercase_	   =     True
       from torch.cuda.amp import autocast

lowercase_	   =     logging.getLogger(__name__)
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__=None      ,	SCREAMING_SNAKE_CASE__=None						):
 return field(default_factory=lambda: default      ,	metadata=SCREAMING_SNAKE_CASE__						)


@dataclass
class 	A_ :
      __snake_case 	=       field(
          metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}   )
      __snake_case 	=       field(
          default=__UpperCamelCase ,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} ,				)
      __snake_case 	=       field(
          default=__UpperCamelCase ,				metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}   )
      __snake_case 	=       field(
          default=0.1 ,				metadata={"""help""": """The dropout ratio for the attention probabilities."""}   )
      __snake_case 	=       field(
          default=0.1 ,				metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""}   )
      __snake_case 	=       field(
          default=0.1 ,				metadata={
              """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
          } ,				)
      __snake_case 	=       field(
          default=0.1 ,				metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""} ,				)
      __snake_case 	=       field(
          default=0.05 ,				metadata={
              """help""": (
                  """Propability of each feature vector along the time axis to be chosen as the start of the vector"""
                  """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"""
                  """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."""
              )
          } ,				)
      __snake_case 	=       field(default=0.0 ,				metadata={"""help""": """The LayerDrop probability."""}   )



@dataclass
class 	A_ :
      __snake_case 	=       field(
          default=__UpperCamelCase ,				metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}   )
      __snake_case 	=       field(
          default="""train+validation""" ,				metadata={
              """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
          } ,				)
      __snake_case 	=       field(
          default=__UpperCamelCase ,				metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}   )
      __snake_case 	=       field(
          default=__UpperCamelCase ,				metadata={"""help""": """The number of processes to use for the preprocessing."""} ,				)
      __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 validation examples to this """
                  """value if set."""
              )
          } ,				)
      __snake_case 	=       list_field(
          default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""] ,				metadata={"""help""": """A list of characters to remove from the transcripts."""} ,				)



@dataclass
class 	A_ :
      __snake_case 	=       42
      __snake_case 	=       True
      __snake_case 	=       None
      __snake_case 	=       None
      __snake_case 	=       None
      __snake_case 	=       None




      def __call__(    self:	int						,				a:	List[Dict[str, Union[List[int], torch.Tensor]]]    ):
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       __lowerCamelCase		:							Tuple		 =						[{'input_values': feature['input_values']} for feature in features]
       __lowerCamelCase		:							Optional[int]		 =						[{'input_ids': feature['labels']} for feature in features]

       __lowerCamelCase		:							Dict		 =						self.processor.pad(
           a						,				padding=self.padding						,				max_length=self.max_length						,				pad_to_multiple_of=self.pad_to_multiple_of						,				return_tensors='pt'						,				)
       __lowerCamelCase		:							Any		 =						self.processor.pad(
           labels=a						,				padding=self.padding						,				max_length=self.max_length_labels						,				pad_to_multiple_of=self.pad_to_multiple_of_labels						,				return_tensors='pt'						,				)

       # replace padding with -100 to ignore loss correctly
       __lowerCamelCase		:							Optional[Any]		 =						labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1    )						,				-100    )

       __lowerCamelCase		:							Dict		 =						labels

       return batch



class 	A_ (	__UpperCamelCase   ):




      def 					_snake_case     (    self:	List[Any]						,				a:	nn.Module						,				a:	Dict[str, Union[torch.Tensor, Any]]    ):
       model.train()
       __lowerCamelCase		:							str		 =						self._prepare_inputs(a    )

       if self.use_amp:
        with autocast():
         __lowerCamelCase		:							Optional[Any]		 =						self.compute_loss(a						,				a    )
       else:
        __lowerCamelCase		:							Optional[int]		 =						self.compute_loss(a						,				a    )

       if self.args.n_gpu > 1:
        if model.module.config.ctc_loss_reduction == "mean":
         __lowerCamelCase		:							Any		 =						loss.mean()
        elif model.module.config.ctc_loss_reduction == "sum":
         __lowerCamelCase		:							Tuple		 =						loss.sum() / (inputs['labels'] >= 0).sum()
        else:
         raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'    )

       if self.args.gradient_accumulation_steps > 1:
        __lowerCamelCase		:							str		 =						loss / self.args.gradient_accumulation_steps

       if self.use_amp:
        self.scaler.scale(a    ).backward()
       elif self.use_apex:
        with amp.scale_loss(a						,				self.optimizer    ) as scaled_loss:
         scaled_loss.backward()
       elif self.deepspeed:
        self.deepspeed.backward(a    )
       else:
        loss.backward()

       return loss.detach()



def 				UpperCamelCase__					(  ):
 # 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.

 __lowerCamelCase		:							Tuple		 =						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.
  __lowerCamelCase		:							Union[str, Any]		 =						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
 else:
  __lowerCamelCase		:							Tuple		 =						parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 __lowerCamelCase		:							Union[str, Any]		 =						None
 if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
  __lowerCamelCase		:							int		 =						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 overcome.'						)
  elif last_checkpoint is not 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.'						)

    # 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						)]      ,	)
 logger.setLevel(logging.INFO if is_main_process(training_args.local_rank						) else logging.WARN						)

 # 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}'						)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank						):
  transformers.utils.logging.set_verbosity_info()
 logger.info('Training/evaluation parameters %s'      ,	SCREAMING_SNAKE_CASE__						)

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

 # Get the datasets:
 __lowerCamelCase		:							Optional[Any]		 =						datasets.load_dataset(
     'common_voice'      ,	data_args.dataset_config_name      ,	split=data_args.train_split_name						)
 __lowerCamelCase		:							str		 =						datasets.load_dataset('common_voice'      ,	data_args.dataset_config_name      ,	split='test'						)

 # Create and save tokenizer
 __lowerCamelCase		:							Tuple		 =						f'[{"".join(data_args.chars_to_ignore						)}]'

 def remove_special_characters(SCREAMING_SNAKE_CASE__						):
  __lowerCamelCase		:							int		 =						re.sub(SCREAMING_SNAKE_CASE__      ,	''      ,	batch['sentence']						).lower() + ' '
  return batch

 __lowerCamelCase		:							Optional[Any]		 =						train_dataset.map(SCREAMING_SNAKE_CASE__      ,	remove_columns=['sentence']						)
 __lowerCamelCase		:							Optional[Any]		 =						eval_dataset.map(SCREAMING_SNAKE_CASE__      ,	remove_columns=['sentence']						)

 def extract_all_chars(SCREAMING_SNAKE_CASE__						):
  __lowerCamelCase		:							Tuple		 =						' '.join(batch['text']						)
  __lowerCamelCase		:							Tuple		 =						list(set(SCREAMING_SNAKE_CASE__						)						)
  return {"vocab": [vocab], "all_text": [all_text]}

 __lowerCamelCase		:							Union[str, Any]		 =						train_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	batched=SCREAMING_SNAKE_CASE__      ,	batch_size=-1      ,	keep_in_memory=SCREAMING_SNAKE_CASE__      ,	remove_columns=train_dataset.column_names      ,	)
 __lowerCamelCase		:							Optional[int]		 =						train_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	batched=SCREAMING_SNAKE_CASE__      ,	batch_size=-1      ,	keep_in_memory=SCREAMING_SNAKE_CASE__      ,	remove_columns=eval_dataset.column_names      ,	)

 __lowerCamelCase		:							Optional[Any]		 =						list(set(vocab_train['vocab'][0]						) | set(vocab_test['vocab'][0]						)						)
 __lowerCamelCase		:							Dict		 =						{v: k for k, v in enumerate(SCREAMING_SNAKE_CASE__						)}
 __lowerCamelCase		:							str		 =						vocab_dict[' ']
 del vocab_dict[" "]
 __lowerCamelCase		:							List[str]		 =						len(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase		:							Tuple		 =						len(SCREAMING_SNAKE_CASE__						)

 with open('vocab.json'      ,	'w'						) as vocab_file:
  json.dump(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 __lowerCamelCase		:							int		 =						WavaVecaCTCTokenizer(
     'vocab.json'      ,	unk_token='[UNK]'      ,	pad_token='[PAD]'      ,	word_delimiter_token='|'      ,	)
 __lowerCamelCase		:							Optional[Any]		 =						WavaVecaFeatureExtractor(
     feature_size=1      ,	sampling_rate=16_000      ,	padding_value=0.0      ,	do_normalize=SCREAMING_SNAKE_CASE__      ,	return_attention_mask=SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase		:							List[str]		 =						WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE__      ,	tokenizer=SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase		:							Tuple		 =						WavaVecaForCTC.from_pretrained(
     model_args.model_name_or_path      ,	cache_dir=model_args.cache_dir      ,	activation_dropout=model_args.activation_dropout      ,	attention_dropout=model_args.attention_dropout      ,	hidden_dropout=model_args.hidden_dropout      ,	feat_proj_dropout=model_args.feat_proj_dropout      ,	mask_time_prob=model_args.mask_time_prob      ,	gradient_checkpointing=training_args.gradient_checkpointing      ,	layerdrop=model_args.layerdrop      ,	ctc_loss_reduction='mean'      ,	pad_token_id=processor.tokenizer.pad_token_id      ,	vocab_size=len(processor.tokenizer						)      ,	)

 if data_args.max_train_samples is not None:
  __lowerCamelCase		:							List[Any]		 =						min(len(SCREAMING_SNAKE_CASE__						)      ,	data_args.max_train_samples						)
  __lowerCamelCase		:							Any		 =						train_dataset.select(range(SCREAMING_SNAKE_CASE__						)						)

 if data_args.max_val_samples is not None:
  __lowerCamelCase		:							Tuple		 =						eval_dataset.select(range(data_args.max_val_samples						)						)

 __lowerCamelCase		:							str		 =						torchaudio.transforms.Resample(48_000      ,	16_000						)

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(SCREAMING_SNAKE_CASE__						):
  __lowerCamelCase		:							Optional[int]		 =						torchaudio.load(batch['path']						)
  __lowerCamelCase		:							Any		 =						resampler(SCREAMING_SNAKE_CASE__						).squeeze().numpy()
  __lowerCamelCase		:							Union[str, Any]		 =						16_000
  __lowerCamelCase		:							Union[str, Any]		 =						batch['text']
  return batch

 __lowerCamelCase		:							Tuple		 =						train_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	remove_columns=train_dataset.column_names      ,	num_proc=data_args.preprocessing_num_workers      ,	)
 __lowerCamelCase		:							List[Any]		 =						eval_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	remove_columns=eval_dataset.column_names      ,	num_proc=data_args.preprocessing_num_workers      ,	)

 def prepare_dataset(SCREAMING_SNAKE_CASE__						):
  # check that all files have the correct sampling rate
  assert (
      len(set(batch['sampling_rate']						)						) == 1
  ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

  __lowerCamelCase		:							str		 =						processor(
      audio=batch['speech']      ,	text=batch['target_text']      ,	sampling_rate=batch['sampling_rate'][0]						)
  batch.update(SCREAMING_SNAKE_CASE__						)
  return batch

 __lowerCamelCase		:							Any		 =						train_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	remove_columns=train_dataset.column_names      ,	batch_size=training_args.per_device_train_batch_size      ,	batched=SCREAMING_SNAKE_CASE__      ,	num_proc=data_args.preprocessing_num_workers      ,	)
 __lowerCamelCase		:							Optional[int]		 =						eval_dataset.map(
     SCREAMING_SNAKE_CASE__      ,	remove_columns=eval_dataset.column_names      ,	batch_size=training_args.per_device_train_batch_size      ,	batched=SCREAMING_SNAKE_CASE__      ,	num_proc=data_args.preprocessing_num_workers      ,	)

 # Metric
 __lowerCamelCase		:							Tuple		 =						datasets.load_metric('wer'						)

 def compute_metrics(SCREAMING_SNAKE_CASE__						):
  __lowerCamelCase		:							Tuple		 =						pred.predictions
  __lowerCamelCase		:							Dict		 =						np.argmax(SCREAMING_SNAKE_CASE__      ,	axis=-1						)

  __lowerCamelCase		:							str		 =						processor.tokenizer.pad_token_id

  __lowerCamelCase		:							Optional[int]		 =						processor.batch_decode(SCREAMING_SNAKE_CASE__						)
  # we do not want to group tokens when computing the metrics
  __lowerCamelCase		:							Union[str, Any]		 =						processor.batch_decode(pred.label_ids      ,	group_tokens=SCREAMING_SNAKE_CASE__						)

  __lowerCamelCase		:							Dict		 =						wer_metric.compute(predictions=SCREAMING_SNAKE_CASE__      ,	references=SCREAMING_SNAKE_CASE__						)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 __lowerCamelCase		:							List[Any]		 =						DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE__      ,	padding=SCREAMING_SNAKE_CASE__						)

 # Initialize our Trainer
 __lowerCamelCase		:							Optional[int]		 =						CTCTrainer(
     model=SCREAMING_SNAKE_CASE__      ,	data_collator=SCREAMING_SNAKE_CASE__      ,	args=SCREAMING_SNAKE_CASE__      ,	compute_metrics=SCREAMING_SNAKE_CASE__      ,	train_dataset=train_dataset if training_args.do_train else None      ,	eval_dataset=eval_dataset if training_args.do_eval else None      ,	tokenizer=processor.feature_extractor      ,	)

 # Training
 if training_args.do_train:
  if last_checkpoint is not None:
   __lowerCamelCase		:							Optional[Any]		 =						last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path						):
   __lowerCamelCase		:							Tuple		 =						model_args.model_name_or_path
  else:
   __lowerCamelCase		:							Any		 =						None

  # Save the feature_extractor and the tokenizer
  if is_main_process(training_args.local_rank						):
   processor.save_pretrained(training_args.output_dir						)

  __lowerCamelCase		:							Union[str, Any]		 =						trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__						)
  trainer.save_model()

  __lowerCamelCase		:							Dict		 =						train_result.metrics
  __lowerCamelCase		:							Optional[Any]		 =						(
      data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE__						)
  )
  __lowerCamelCase		:							Any		 =						min(SCREAMING_SNAKE_CASE__      ,	len(SCREAMING_SNAKE_CASE__						)						)

  trainer.log_metrics('train'      ,	SCREAMING_SNAKE_CASE__						)
  trainer.save_metrics('train'      ,	SCREAMING_SNAKE_CASE__						)
  trainer.save_state()

 # Evaluation
 __lowerCamelCase		:							int		 =						{}
 if training_args.do_eval:
  logger.info('*** Evaluate ***'						)
  __lowerCamelCase		:							Union[str, Any]		 =						trainer.evaluate()
  __lowerCamelCase		:							Any		 =						data_args.max_val_samples if data_args.max_val_samples is not None else len(SCREAMING_SNAKE_CASE__						)
  __lowerCamelCase		:							Union[str, Any]		 =						min(SCREAMING_SNAKE_CASE__      ,	len(SCREAMING_SNAKE_CASE__						)						)

  trainer.log_metrics('eval'      ,	SCREAMING_SNAKE_CASE__						)
  trainer.save_metrics('eval'      ,	SCREAMING_SNAKE_CASE__						)

 return results


if __name__ == "__main__":
       main()





import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
       import jax
       import jax.numpy as jnp

       from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor


class 	A_ (	unittest.TestCase   ):




      '''simple docstring'''


      def __init__(    self:	int						,				a:	Optional[Any]						,				a:	Optional[Any]=3						,				a:	List[str]=32						,				a:	Optional[int]=3						,				a:	Any=10						,				a:	List[str]=[10, 20, 30, 40]						,				a:	Any=[1, 1, 2, 1]						,				a:	Optional[int]=True						,				a:	List[str]=True						,				a:	Tuple="relu"						,				a:	List[Any]=3						,				a:	List[Any]=None						,				):
       __lowerCamelCase		:							Union[str, Any]		 =						parent
       __lowerCamelCase		:							Any		 =						batch_size
       __lowerCamelCase		:							List[str]		 =						image_size
       __lowerCamelCase		:							Tuple		 =						num_channels
       __lowerCamelCase		:							int		 =						embeddings_size
       __lowerCamelCase		:							Optional[int]		 =						hidden_sizes
       __lowerCamelCase		:							Optional[Any]		 =						depths
       __lowerCamelCase		:							Optional[int]		 =						is_training
       __lowerCamelCase		:							List[str]		 =						use_labels
       __lowerCamelCase		:							Dict		 =						hidden_act
       __lowerCamelCase		:							Union[str, Any]		 =						num_labels
       __lowerCamelCase		:							Tuple		 =						scope
       __lowerCamelCase		:							Union[str, Any]		 =						len(a    )




      def 					_snake_case     (    self:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

       __lowerCamelCase		:							List[str]		 =						self.get_config()

       return config, pixel_values




      def 					_snake_case     (    self:	List[str]    ):
       return RegNetConfig(
           num_channels=self.num_channels						,				embeddings_size=self.embeddings_size						,				hidden_sizes=self.hidden_sizes						,				depths=self.depths						,				hidden_act=self.hidden_act						,				num_labels=self.num_labels						,				image_size=self.image_size						,				)




      def 					_snake_case     (    self:	Tuple						,				a:	Optional[int]						,				a:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						FlaxRegNetModel(config=a    )
       __lowerCamelCase		:							List[str]		 =						model(a    )

       # Output shape (b, c, h, w)
       self.parent.assertEqual(
           result.last_hidden_state.shape						,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,				)




      def 					_snake_case     (    self:	Optional[int]						,				a:	List[Any]						,				a:	List[Any]    ):
       __lowerCamelCase		:							Tuple		 =						self.num_labels
       __lowerCamelCase		:							Union[str, Any]		 =						FlaxRegNetForImageClassification(config=a    )
       __lowerCamelCase		:							List[Any]		 =						model(a    )
       self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)    )




      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							Union[str, Any]		 =						self.prepare_config_and_inputs()
       __lowerCamelCase ,					__lowerCamelCase		:							str		 =						config_and_inputs
       __lowerCamelCase		:							Tuple		 =						{'pixel_values': pixel_values}
       return config, inputs_dict



@require_flax
class 	A_ (	__UpperCamelCase ,				unittest.TestCase   ):




      '''simple docstring'''


      __snake_case 	=       (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

      __snake_case 	=       False
      __snake_case 	=       False
      __snake_case 	=       False




      def 					_snake_case     (    self:	Tuple    ):
       __lowerCamelCase		:							Dict		 =						FlaxRegNetModelTester(self    )
       __lowerCamelCase		:							List[str]		 =						ConfigTester(self						,				config_class=a						,				has_text_modality=a    )




      def 					_snake_case     (    self:	Union[str, Any]    ):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()




      def 					_snake_case     (    self:	List[Any]    ):
       return




      def 					_snake_case     (    self:	Dict    ):
       __lowerCamelCase		:							Union[str, Any]		 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a    )




      def 					_snake_case     (    self:	Optional[int]    ):
       __lowerCamelCase		:							Union[str, Any]		 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a    )




      @unittest.skip(reason='RegNet does not use inputs_embeds'    )
      def 					_snake_case     (    self:	Tuple    ):
       pass




      @unittest.skip(reason='RegNet does not support input and output embeddings'    )
      def 					_snake_case     (    self:	str    ):
       pass




      def 					_snake_case     (    self:	List[Any]    ):
       __lowerCamelCase ,					__lowerCamelCase		:							Optional[Any]		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							Optional[Any]		 =						model_class(a    )
        __lowerCamelCase		:							Dict		 =						inspect.signature(model.__call__    )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        __lowerCamelCase		:							Union[str, Any]		 =						[*signature.parameters.keys()]

        __lowerCamelCase		:							Union[str, Any]		 =						['pixel_values']
        self.assertListEqual(arg_names[:1]						,				a    )




      def 					_snake_case     (    self:	List[str]    ):
       def check_hidden_states_output(a:	List[Any]						,				a:	List[Any]						,				a:	Union[str, Any]    ):
        __lowerCamelCase		:							str		 =						model_class(a    )

        __lowerCamelCase		:							Optional[Any]		 =						model(**self._prepare_for_class(a						,				a    )    )

        __lowerCamelCase		:							List[str]		 =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        __lowerCamelCase		:							List[str]		 =						self.model_tester.num_stages
        self.assertEqual(len(a    )						,				expected_num_stages + 1    )

       __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							int		 =						True
        check_hidden_states_output(a						,				a						,				a    )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCamelCase		:							List[Any]		 =						True

        check_hidden_states_output(a						,				a						,				a    )




      def 					_snake_case     (    self:	Dict    ):
       __lowerCamelCase ,					__lowerCamelCase		:							Optional[int]		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__    ):
         __lowerCamelCase		:							str		 =						self._prepare_for_class(a						,				a    )
         __lowerCamelCase		:							List[str]		 =						model_class(a    )

         @jax.jit
         def model_jitted(a:	Optional[int]						,				**a:	str    ):
          return model(pixel_values=a						,				**a    )

         with self.subTest('JIT Enabled'    ):
          __lowerCamelCase		:							List[str]		 =						model_jitted(**a    ).to_tuple()

         with self.subTest('JIT Disabled'    ):
          with jax.disable_jit():
           __lowerCamelCase		:							Optional[int]		 =						model_jitted(**a    ).to_tuple()

         self.assertEqual(len(a    )						,				len(a    )    )
         for jitted_output, output in zip(a						,				a    ):
          self.assertEqual(jitted_output.shape						,				output.shape    )



def 				UpperCamelCase__					(  ):
 __lowerCamelCase		:							List[str]		 =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
 return image



@require_flax
class 	A_ (	unittest.TestCase   ):




      '''simple docstring'''


      @cached_property
      def 					_snake_case     (    self:	Tuple    ):
       return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'    ) if is_vision_available() else None




      @slow
      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							Optional[Any]		 =						FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'    )

       __lowerCamelCase		:							Tuple		 =						self.default_image_processor
       __lowerCamelCase		:							int		 =						prepare_img()
       __lowerCamelCase		:							Tuple		 =						image_processor(images=a						,				return_tensors='np'    )

       __lowerCamelCase		:							List[Any]		 =						model(**a    )

       # verify the logits
       __lowerCamelCase		:							str		 =						(1, 1000)
       self.assertEqual(outputs.logits.shape						,				a    )

       __lowerCamelCase		:							int		 =						jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]    )

       self.assertTrue(jnp.allclose(outputs.logits[0, :3]						,				a						,				atol=1e-4    )    )

