


"""simple docstring"""


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'):
   __snake_case    					=					True
   from torch.cuda.amp import autocast

__snake_case    					=					logging.getLogger(__name__)


def    _lowerCamelCase   (     lowerCamelCase__	:							Union[str, Any]=None       ,		lowerCamelCase__	:							str=None  ):
 return field(default_factory=lambda: default       ,		metadata=lowerCamelCase__  )

@dataclass
class 				_SCREAMING_SNAKE_CASE				:
   """simple docstring"""



   _a   :       str									=    field(
       metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}  )
   _a   :       Optional[str]									=    field(
       default=__UpperCAmelCase     ,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}     ,   )
   _a   :       Optional[bool]									=    field(
       default=__UpperCAmelCase     ,   metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}  )
   _a   :       Optional[float]									=    field(
       default=0.1     ,   metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}  )
   _a   :       Optional[float]									=    field(
       default=0.1     ,   metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}  )
   _a   :       Optional[float]									=    field(
       default=0.1     ,   metadata={
           '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
       }     ,   )
   _a   :       Optional[float]									=    field(
       default=0.1     ,   metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}     ,   )
   _a   :       Optional[float]									=    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``.'''
           )
       }     ,   )
   _a   :       Optional[float]									=    field(default=0.0     ,   metadata={'''help''': '''The LayerDrop probability.'''}  )

@dataclass
class 				_SCREAMING_SNAKE_CASE				:
   """simple docstring"""



   _a   :       Optional[str]									=    field(
       default=__UpperCAmelCase     ,   metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}  )
   _a   :       Optional[str]									=    field(
       default='''train+validation'''     ,   metadata={
           '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
       }     ,   )
   _a   :       bool									=    field(
       default=__UpperCAmelCase     ,   metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}  )
   _a   :       Optional[int]									=    field(
       default=__UpperCAmelCase     ,   metadata={'''help''': '''The number of processes to use for the preprocessing.'''}     ,   )
   _a   :       Optional[int]									=    field(
       default=__UpperCAmelCase     ,   metadata={
           '''help''': (
               '''For debugging purposes or quicker training, truncate the number of training examples to this '''
               '''value if set.'''
           )
       }     ,   )
   _a   :       Optional[int]									=    field(
       default=__UpperCAmelCase     ,   metadata={
           '''help''': (
               '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
               '''value if set.'''
           )
       }     ,   )
   _a   :       List[str]									=    list_field(
       default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']     ,   metadata={'''help''': '''A list of characters to remove from the transcripts.'''}     ,   )

@dataclass
class 				_SCREAMING_SNAKE_CASE				:
   """simple docstring"""



   _a   :       WavaVecaProcessor
   _a   :       Union[bool, str]									=    True
   _a   :       Optional[int]									=    None
   _a   :       Optional[int]									=    None
   _a   :       Optional[int]									=    None
   _a   :       Optional[int]									=    None


   def __call__(						self ,     lowerCamelCase__						)      ->							Dict[str, torch.Tensor]:
    # split inputs and labels since they have to be of different lenghts and need
    # different padding methods
    lowercase__       :       Dict				=						[{"""input_values""": feature["""input_values"""]} for feature in features]
    lowercase__       :       Tuple				=						[{"""input_ids""": feature["""labels"""]} for feature in features]

    lowercase__       :       List[str]				=						self.processor.pad(
        lowerCamelCase__ ,     padding=self.padding ,     max_length=self.max_length ,     pad_to_multiple_of=self.pad_to_multiple_of ,     return_tensors="""pt""" ,     )
    lowercase__       :       Any				=						self.processor.pad(
        labels=lowerCamelCase__ ,     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
    lowercase__       :       Optional[int]				=						labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1						) ,     -100						)

    lowercase__       :       Any				=						labels

    return batch

class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							torch.Tensor:
    model.train()
    lowercase__       :       Dict				=						self._prepare_inputs(lowerCamelCase__						)

    if self.use_amp:
     with autocast():
      lowercase__       :       List[str]				=						self.compute_loss(lowerCamelCase__ ,     lowerCamelCase__						)
    else:
     lowercase__       :       int				=						self.compute_loss(lowerCamelCase__ ,     lowerCamelCase__						)

    if self.args.n_gpu > 1:
     if model.module.config.ctc_loss_reduction == "mean":
      lowercase__       :       Tuple				=						loss.mean()
     elif model.module.config.ctc_loss_reduction == "sum":
      lowercase__       :       Optional[int]				=						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:
     lowercase__       :       Tuple				=						loss / self.args.gradient_accumulation_steps

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

    return loss.detach()


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

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

 # Detecting last checkpoint.
 lowercase__       :       Tuple				=						None
 if os.path.isdir(training_args.output_dir  ) and training_args.do_train and not training_args.overwrite_output_dir:
  lowercase__       :       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 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"""       ,		lowerCamelCase__  )

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

 # Get the datasets:
 lowercase__       :       Union[str, Any]				=						datasets.load_dataset(
     """common_voice"""       ,		data_args.dataset_config_name       ,		split=data_args.train_split_name  )
 lowercase__       :       List[Any]				=						datasets.load_dataset("""common_voice"""       ,		data_args.dataset_config_name       ,		split="""test"""  )

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

 def remove_special_characters(lowerCamelCase__	:							Optional[int]  ):
  lowercase__       :       Any				=						re.sub(lowerCamelCase__       ,		""""""       ,		batch["""sentence"""]  ).lower() + """ """
  return batch

 lowercase__       :       Any				=						train_dataset.map(lowerCamelCase__       ,		remove_columns=["""sentence"""]  )
 lowercase__       :       Tuple				=						eval_dataset.map(lowerCamelCase__       ,		remove_columns=["""sentence"""]  )

 def extract_all_chars(lowerCamelCase__	:							Union[str, Any]  ):
  lowercase__       :       Optional[Any]				=						""" """.join(batch["""text"""]  )
  lowercase__       :       Optional[int]				=						list(set(lowerCamelCase__  )  )
  return {"vocab": [vocab], "all_text": [all_text]}

 lowercase__       :       str				=						train_dataset.map(
     lowerCamelCase__       ,		batched=lowerCamelCase__       ,		batch_size=-1       ,		keep_in_memory=lowerCamelCase__       ,		remove_columns=train_dataset.column_names       ,		)
 lowercase__       :       Union[str, Any]				=						train_dataset.map(
     lowerCamelCase__       ,		batched=lowerCamelCase__       ,		batch_size=-1       ,		keep_in_memory=lowerCamelCase__       ,		remove_columns=eval_dataset.column_names       ,		)

 lowercase__       :       Optional[int]				=						list(set(vocab_train["""vocab"""][0]  ) | set(vocab_test["""vocab"""][0]  )  )
 lowercase__       :       Optional[int]				=						{v: k for k, v in enumerate(lowerCamelCase__  )}
 lowercase__       :       Union[str, Any]				=						vocab_dict[""" """]
 del vocab_dict[" "]
 lowercase__       :       Any				=						len(lowerCamelCase__  )
 lowercase__       :       Tuple				=						len(lowerCamelCase__  )

 with open("""vocab.json"""       ,		"""w"""  ) as vocab_file:
  json.dump(lowerCamelCase__       ,		lowerCamelCase__  )

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 lowercase__       :       List[str]				=						WavaVecaCTCTokenizer(
     """vocab.json"""       ,		unk_token="""[UNK]"""       ,		pad_token="""[PAD]"""       ,		word_delimiter_token="""|"""       ,		)
 lowercase__       :       Union[str, Any]				=						WavaVecaFeatureExtractor(
     feature_size=1       ,		sampling_rate=1_60_00       ,		padding_value=0.0       ,		do_normalize=lowerCamelCase__       ,		return_attention_mask=lowerCamelCase__  )
 lowercase__       :       List[Any]				=						WavaVecaProcessor(feature_extractor=lowerCamelCase__       ,		tokenizer=lowerCamelCase__  )
 lowercase__       :       Optional[int]				=						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:
  lowercase__       :       int				=						min(len(lowerCamelCase__  )       ,		data_args.max_train_samples  )
  lowercase__       :       int				=						train_dataset.select(range(lowerCamelCase__  )  )

 if data_args.max_val_samples is not None:
  lowercase__       :       str				=						eval_dataset.select(range(data_args.max_val_samples  )  )

 lowercase__       :       List[str]				=						torchaudio.transforms.Resample(4_80_00       ,		1_60_00  )

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(lowerCamelCase__	:							List[str]  ):
  lowercase__	,       lowercase__       :       Dict				=						torchaudio.load(batch["""path"""]  )
  lowercase__       :       List[str]				=						resampler(lowerCamelCase__  ).squeeze().numpy()
  lowercase__       :       Optional[Any]				=						1_60_00
  lowercase__       :       Optional[int]				=						batch["""text"""]
  return batch

 lowercase__       :       Optional[Any]				=						train_dataset.map(
     lowerCamelCase__       ,		remove_columns=train_dataset.column_names       ,		num_proc=data_args.preprocessing_num_workers       ,		)
 lowercase__       :       Optional[Any]				=						eval_dataset.map(
     lowerCamelCase__       ,		remove_columns=eval_dataset.column_names       ,		num_proc=data_args.preprocessing_num_workers       ,		)

 def prepare_dataset(lowerCamelCase__	:							str  ):
  # 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}.'''

  lowercase__       :       Tuple				=						processor(
      audio=batch["""speech"""]       ,		text=batch["""target_text"""]       ,		sampling_rate=batch["""sampling_rate"""][0]  )
  batch.update(lowerCamelCase__  )
  return batch

 lowercase__       :       Tuple				=						train_dataset.map(
     lowerCamelCase__       ,		remove_columns=train_dataset.column_names       ,		batch_size=training_args.per_device_train_batch_size       ,		batched=lowerCamelCase__       ,		num_proc=data_args.preprocessing_num_workers       ,		)
 lowercase__       :       List[Any]				=						eval_dataset.map(
     lowerCamelCase__       ,		remove_columns=eval_dataset.column_names       ,		batch_size=training_args.per_device_train_batch_size       ,		batched=lowerCamelCase__       ,		num_proc=data_args.preprocessing_num_workers       ,		)

 # Metric
 lowercase__       :       int				=						datasets.load_metric("""wer"""  )

 def compute_metrics(lowerCamelCase__	:							str  ):
  lowercase__       :       Optional[Any]				=						pred.predictions
  lowercase__       :       Tuple				=						np.argmax(lowerCamelCase__       ,		axis=-1  )

  lowercase__       :       Dict				=						processor.tokenizer.pad_token_id

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

  lowercase__       :       Optional[Any]				=						wer_metric.compute(predictions=lowerCamelCase__       ,		references=lowerCamelCase__  )

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 lowercase__       :       Any				=						DataCollatorCTCWithPadding(processor=lowerCamelCase__       ,		padding=lowerCamelCase__  )

 # Initialize our Trainer
 lowercase__       :       Dict				=						CTCTrainer(
     model=lowerCamelCase__       ,		data_collator=lowerCamelCase__       ,		args=lowerCamelCase__       ,		compute_metrics=lowerCamelCase__       ,		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:
   lowercase__       :       List[Any]				=						last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path  ):
   lowercase__       :       Union[str, Any]				=						model_args.model_name_or_path
  else:
   lowercase__       :       Optional[int]				=						None

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

  lowercase__       :       Optional[Any]				=						trainer.train(resume_from_checkpoint=lowerCamelCase__  )
  trainer.save_model()

  lowercase__       :       int				=						train_result.metrics
  lowercase__       :       Tuple				=						(
      data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase__  )
  )
  lowercase__       :       Optional[Any]				=						min(lowerCamelCase__       ,		len(lowerCamelCase__  )  )

  trainer.log_metrics("""train"""       ,		lowerCamelCase__  )
  trainer.save_metrics("""train"""       ,		lowerCamelCase__  )
  trainer.save_state()

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

  trainer.log_metrics("""eval"""       ,		lowerCamelCase__  )
  trainer.save_metrics("""eval"""       ,		lowerCamelCase__  )

 return results


if __name__ == "__main__":
   main()



"""simple docstring"""


import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
   from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor

class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							Union[str, Any]:
    lowercase__       :       Optional[Any]				=						self.config_class(**self.inputs_dict						)
    self.parent.assertTrue(hasattr(lowerCamelCase__ ,     """tf_padding"""						)						)
    self.parent.assertTrue(hasattr(lowerCamelCase__ ,     """depth_multiplier"""						)						)

class 				_SCREAMING_SNAKE_CASE				:
   """simple docstring"""



   def __init__(						self ,     lowerCamelCase__ ,     lowerCamelCase__=13 ,     lowerCamelCase__=3 ,     lowerCamelCase__=32 ,     lowerCamelCase__=0.25 ,     lowerCamelCase__=8 ,     lowerCamelCase__=8 ,     lowerCamelCase__=6 ,     lowerCamelCase__=32 ,     lowerCamelCase__=True ,     lowerCamelCase__=True ,     lowerCamelCase__=True ,     lowerCamelCase__="relu6" ,     lowerCamelCase__=1280 ,     lowerCamelCase__=0.1 ,     lowerCamelCase__=0.02 ,     lowerCamelCase__=True ,     lowerCamelCase__=True ,     lowerCamelCase__=10 ,     lowerCamelCase__=None ,     )      ->							List[Any]:
    lowercase__       :       int				=						parent
    lowercase__       :       Any				=						batch_size
    lowercase__       :       Optional[int]				=						num_channels
    lowercase__       :       int				=						image_size
    lowercase__       :       Tuple				=						depth_multiplier
    lowercase__       :       Tuple				=						depth_divisible_by
    lowercase__       :       str				=						min_depth
    lowercase__       :       int				=						expand_ratio
    lowercase__       :       List[str]				=						tf_padding
    lowercase__       :       Union[str, Any]				=						output_stride
    lowercase__       :       Optional[int]				=						first_layer_is_expansion
    lowercase__       :       Optional[Any]				=						finegrained_output
    lowercase__       :       Union[str, Any]				=						hidden_act
    lowercase__       :       List[Any]				=						last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier						)
    lowercase__       :       Union[str, Any]				=						classifier_dropout_prob
    lowercase__       :       str				=						use_labels
    lowercase__       :       Optional[Any]				=						is_training
    lowercase__       :       List[Any]				=						num_labels
    lowercase__       :       List[str]				=						initializer_range
    lowercase__       :       Optional[int]				=						scope


   def 					UpperCAmelCase__(						self						)      ->							Any:
    lowercase__       :       Dict				=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

    lowercase__       :       List[str]				=						None
    lowercase__       :       Tuple				=						None
    if self.use_labels:
     lowercase__       :       Optional[Any]				=						ids_tensor([self.batch_size] ,     self.num_labels						)
     lowercase__       :       Dict				=						ids_tensor([self.batch_size, self.image_size, self.image_size] ,     self.num_labels						)

    lowercase__       :       Dict				=						self.get_config()

    return config, pixel_values, labels, pixel_labels


   def 					UpperCAmelCase__(						self						)      ->							int:
    return MobileNetVaConfig(
        num_channels=self.num_channels ,     image_size=self.image_size ,     depth_multiplier=self.depth_multiplier ,     depth_divisible_by=self.depth_divisible_by ,     min_depth=self.min_depth ,     expand_ratio=self.expand_ratio ,     output_stride=self.output_stride ,     first_layer_is_expansion=self.first_layer_is_expansion ,     finegrained_output=self.finegrained_output ,     hidden_act=self.hidden_act ,     tf_padding=self.tf_padding ,     classifier_dropout_prob=self.classifier_dropout_prob ,     initializer_range=self.initializer_range ,     )


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							Dict:
    lowercase__       :       str				=						MobileNetVaModel(config=lowerCamelCase__						)
    model.to(lowerCamelCase__						)
    model.eval()
    lowercase__       :       List[Any]				=						model(lowerCamelCase__						)
    self.parent.assertEqual(
        result.last_hidden_state.shape ,     (
            self.batch_size,
            self.last_hidden_size,
            self.image_size // self.output_stride,
            self.image_size // self.output_stride,
        ) ,     )
    self.parent.assertEqual(
        result.pooler_output.shape ,     (self.batch_size, self.last_hidden_size) ,     )


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							List[Any]:
    lowercase__       :       Optional[int]				=						self.num_labels
    lowercase__       :       List[str]				=						MobileNetVaForImageClassification(lowerCamelCase__						)
    model.to(lowerCamelCase__						)
    model.eval()
    lowercase__       :       Dict				=						model(lowerCamelCase__ ,     labels=lowerCamelCase__						)
    self.parent.assertEqual(result.logits.shape ,     (self.batch_size, self.num_labels)						)


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						)      ->							str:
    lowercase__       :       Dict				=						self.num_labels
    lowercase__       :       List[Any]				=						MobileNetVaForSemanticSegmentation(lowerCamelCase__						)
    model.to(lowerCamelCase__						)
    model.eval()
    lowercase__       :       List[Any]				=						model(lowerCamelCase__						)
    self.parent.assertEqual(
        result.logits.shape ,     (
            self.batch_size,
            self.num_labels,
            self.image_size // self.output_stride,
            self.image_size // self.output_stride,
        ) ,     )
    lowercase__       :       Tuple				=						model(lowerCamelCase__ ,     labels=lowerCamelCase__						)
    self.parent.assertEqual(
        result.logits.shape ,     (
            self.batch_size,
            self.num_labels,
            self.image_size // self.output_stride,
            self.image_size // self.output_stride,
        ) ,     )







   def 					UpperCAmelCase__(						self						)      ->							int:
    lowercase__       :       Optional[int]				=						self.prepare_config_and_inputs()
    lowercase__	,       lowercase__	,       lowercase__	,       lowercase__       :       Tuple				=						config_and_inputs
    lowercase__       :       List[Any]				=						{"""pixel_values""": pixel_values}
    return config, inputs_dict

@require_torch
class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase     ,   __UpperCAmelCase     ,   unittest.TestCase  ):
   """simple docstring"""



   _a   :       Optional[int]									=    (
       (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   _a   :       Tuple									=    (
       {
           '''feature-extraction''': MobileNetVaModel,
           '''image-classification''': MobileNetVaForImageClassification,
           '''image-segmentation''': MobileNetVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   _a   :       List[str]									=    False
   _a   :       int									=    False
   _a   :       Optional[Any]									=    False
   _a   :       List[str]									=    False


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       List[Any]				=						MobileNetVaModelTester(self						)
    lowercase__       :       Any				=						MobileNetVaConfigTester(self ,     config_class=lowerCamelCase__ ,     has_text_modality=lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							Union[str, Any]:
    self.config_tester.run_common_tests()


   @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds"""						)
   def 					UpperCAmelCase__(						self						)      ->							str:
    pass


   @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings"""						)
   def 					UpperCAmelCase__(						self						)      ->							List[Any]:
    pass


   @unittest.skip(reason="""MobileNetV2 does not output attentions"""						)
   def 					UpperCAmelCase__(						self						)      ->							List[Any]:
    pass


   def 					UpperCAmelCase__(						self						)      ->							str:
    lowercase__	,       lowercase__       :       Optional[int]				=						self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     lowercase__       :       Union[str, Any]				=						model_class(lowerCamelCase__						)
     lowercase__       :       List[Any]				=						inspect.signature(model.forward						)
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     lowercase__       :       Union[str, Any]				=						[*signature.parameters.keys()]

     lowercase__       :       Union[str, Any]				=						["""pixel_values"""]
     self.assertListEqual(arg_names[:1] ,     lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							Union[str, Any]:
    lowercase__       :       Any				=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							Any:
    def check_hidden_states_output(lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						):
     lowercase__       :       Optional[int]				=						model_class(lowerCamelCase__						)
     model.to(lowerCamelCase__						)
     model.eval()

     with torch.no_grad():
      lowercase__       :       str				=						model(**self._prepare_for_class(lowerCamelCase__ ,     lowerCamelCase__						)						)

     lowercase__       :       int				=						outputs.hidden_states

     lowercase__       :       Optional[int]				=						16
     self.assertEqual(len(lowerCamelCase__						) ,     lowerCamelCase__						)

    lowercase__	,       lowercase__       :       List[str]				=						self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     lowercase__       :       Tuple				=						True
     check_hidden_states_output(lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     lowercase__       :       Union[str, Any]				=						True

     check_hidden_states_output(lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							str:
    lowercase__       :       Union[str, Any]				=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__						)


   def 					UpperCAmelCase__(						self						)      ->							str:
    lowercase__       :       str				=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__						)







   @slow
   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowercase__       :       List[str]				=						MobileNetVaModel.from_pretrained(lowerCamelCase__						)
     self.assertIsNotNone(lowerCamelCase__						)


def    _lowerCamelCase   (     ):
 lowercase__       :       List[Any]				=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
 return image






@require_torch
@require_vision
class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   @cached_property
   def 					UpperCAmelCase__(						self						)      ->							Optional[Any]:
    return (
        MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224"""						) if is_vision_available() else None
    )


   @slow
   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Union[str, Any]				=						MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224"""						).to(lowerCamelCase__						)

    lowercase__       :       int				=						self.default_image_processor
    lowercase__       :       str				=						prepare_img()
    lowercase__       :       Optional[int]				=						image_processor(images=lowerCamelCase__ ,     return_tensors="""pt"""						).to(lowerCamelCase__						)

    # forward pass
    with torch.no_grad():
     lowercase__       :       Optional[Any]				=						model(**lowerCamelCase__						)

    # verify the logits
    lowercase__       :       List[Any]				=						torch.Size((1, 1001)						)
    self.assertEqual(outputs.logits.shape ,     lowerCamelCase__						)

    lowercase__       :       List[Any]				=						torch.tensor([0.2445, -1.1993, 0.1905]						).to(lowerCamelCase__						)

    self.assertTrue(torch.allclose(outputs.logits[0, :3] ,     lowerCamelCase__ ,     atol=1E-4						)						)







   @slow
   def 					UpperCAmelCase__(						self						)      ->							List[str]:
    lowercase__       :       Any				=						MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""						)
    lowercase__       :       Optional[int]				=						model.to(lowerCamelCase__						)

    lowercase__       :       int				=						MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""						)

    lowercase__       :       Tuple				=						prepare_img()
    lowercase__       :       int				=						image_processor(images=lowerCamelCase__ ,     return_tensors="""pt"""						).to(lowerCamelCase__						)

    # forward pass
    with torch.no_grad():
     lowercase__       :       List[Any]				=						model(**lowerCamelCase__						)
    lowercase__       :       int				=						outputs.logits

    # verify the logits
    lowercase__       :       Any				=						torch.Size((1, 21, 65, 65)						)
    self.assertEqual(logits.shape ,     lowerCamelCase__						)

    lowercase__       :       Union[str, Any]				=						torch.tensor(
        [
            [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
            [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
            [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
        ] ,     device=lowerCamelCase__ ,     )

    self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,     lowerCamelCase__ ,     atol=1E-4						)						)