

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

lowerCAmelCase__								=		logging.getLogger(__name__)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Optional[Any]=None							,       UpperCAmelCase_							:     Any=None	)						->				List[str]:




	'''simple docstring'''




	return field(default_factory=lambda: default							,       metadata=UpperCAmelCase_	)







@dataclass
class 	lowercase    :


		"""simple docstring"""




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







@dataclass
class 	lowercase    :


		"""simple docstring"""




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







@dataclass
class 	lowercase    :


		"""simple docstring"""




		a__					       =  42
		a__					       =  True
		a__					       =  None
		a__					       =  None
		a__					       =  None
		a__					       =  None


		def __call__(				self	,       __snake_case):
			# split inputs and labels since they have to be of different lenghts and need
			# different padding methods
			_UpperCamelCase   :		Union[str, Any]			=						[{'input_values': feature['input_values']} for feature in features]
			_UpperCamelCase   :		Optional[int]			=						[{'input_ids': feature['labels']} for feature in features]

			_UpperCamelCase   :		int			=						self.processor.pad(
			    __snake_case	,       padding=self.padding	,       max_length=self.max_length	,       pad_to_multiple_of=self.pad_to_multiple_of	,       return_tensors='pt'	,       )
			_UpperCamelCase   :		Optional[int]			=						self.processor.pad(
			    labels=__snake_case	,       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
			_UpperCamelCase   :		Optional[int]			=						labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1)	,       -1_00)

			_UpperCamelCase   :		Union[str, Any]			=						labels

			return batch







class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		def 		A__					(				self	,       __snake_case	,       __snake_case):
			model.train()
			_UpperCamelCase   :		Optional[int]			=						self._prepare_inputs(__snake_case)

			if self.use_amp:
				with autocast():
					_UpperCamelCase   :		Optional[int]			=						self.compute_loss(__snake_case	,       __snake_case)
			else:
				_UpperCamelCase   :		Union[str, Any]			=						self.compute_loss(__snake_case	,       __snake_case)

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

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

			return loss.detach()






def 					lowerCamelCase_     (							)						->				Optional[Any]:




	'''simple docstring'''




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

	# Detecting last checkpoint.
	_UpperCamelCase   :		Optional[Any]			=						None
	if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
		_UpperCamelCase   :		Optional[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'							,       UpperCAmelCase_	)

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

	# Get the datasets:
	_UpperCamelCase   :		Tuple			=						datasets.load_dataset(
	    'common_voice'							,       data_args.dataset_config_name							,       split=data_args.train_split_name	)
	_UpperCamelCase   :		List[Any]			=						datasets.load_dataset('common_voice'							,       data_args.dataset_config_name							,       split='test'	)

	# Create and save tokenizer
	_UpperCamelCase   :		List[Any]			=						F'''[{"".join(data_args.chars_to_ignore	)}]'''

	def remove_special_characters(UpperCAmelCase_							:     Dict	):
		_UpperCamelCase   :		Tuple			=						re.sub(UpperCAmelCase_							,       ''							,       batch['sentence']	).lower() + ' '
		return batch

	_UpperCamelCase   :		List[Any]			=						train_dataset.map(UpperCAmelCase_							,       remove_columns=['sentence']	)
	_UpperCamelCase   :		List[str]			=						eval_dataset.map(UpperCAmelCase_							,       remove_columns=['sentence']	)

	def extract_all_chars(UpperCAmelCase_							:     Any	):
		_UpperCamelCase   :		Any			=						' '.join(batch['text']	)
		_UpperCamelCase   :		int			=						list(set(UpperCAmelCase_	)	)
		return {"vocab": [vocab], "all_text": [all_text]}

	_UpperCamelCase   :		Dict			=						train_dataset.map(
	    UpperCAmelCase_							,       batched=UpperCAmelCase_							,       batch_size=-1							,       keep_in_memory=UpperCAmelCase_							,       remove_columns=train_dataset.column_names							,       )
	_UpperCamelCase   :		Optional[Any]			=						train_dataset.map(
	    UpperCAmelCase_							,       batched=UpperCAmelCase_							,       batch_size=-1							,       keep_in_memory=UpperCAmelCase_							,       remove_columns=eval_dataset.column_names							,       )

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

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

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

	if data_args.max_val_samples is not None:
		_UpperCamelCase   :		Any			=						eval_dataset.select(range(data_args.max_val_samples	)	)

	_UpperCamelCase   :		Any			=						torchaudio.transforms.Resample(4_8_0_0_0							,       1_6_0_0_0	)

	# Preprocessing the datasets.
	# We need to read the aduio files as arrays and tokenize the targets.
	def speech_file_to_array_fn(UpperCAmelCase_							:     List[str]	):
		_UpperCamelCase	,		_UpperCamelCase   :		List[str]			=						torchaudio.load(batch['path']	)
		_UpperCamelCase   :		Union[str, Any]			=						resampler(UpperCAmelCase_	).squeeze().numpy()
		_UpperCamelCase   :		Union[str, Any]			=						1_6_0_0_0
		_UpperCamelCase   :		Union[str, Any]			=						batch['text']
		return batch

	_UpperCamelCase   :		int			=						train_dataset.map(
	    UpperCAmelCase_							,       remove_columns=train_dataset.column_names							,       num_proc=data_args.preprocessing_num_workers							,       )
	_UpperCamelCase   :		Union[str, Any]			=						eval_dataset.map(
	    UpperCAmelCase_							,       remove_columns=eval_dataset.column_names							,       num_proc=data_args.preprocessing_num_workers							,       )

	def prepare_dataset(UpperCAmelCase_							:     List[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}.'''

		_UpperCamelCase   :		int			=						processor(
		    audio=batch['speech']							,       text=batch['target_text']							,       sampling_rate=batch['sampling_rate'][0]	)
		batch.update(UpperCAmelCase_	)
		return batch

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

	# Metric
	_UpperCamelCase   :		Union[str, Any]			=						datasets.load_metric('wer'	)

	def compute_metrics(UpperCAmelCase_							:     Tuple	):
		_UpperCamelCase   :		Optional[Any]			=						pred.predictions
		_UpperCamelCase   :		List[Any]			=						np.argmax(UpperCAmelCase_							,       axis=-1	)

		_UpperCamelCase   :		Optional[Any]			=						processor.tokenizer.pad_token_id

		_UpperCamelCase   :		Any			=						processor.batch_decode(UpperCAmelCase_	)
		# we do not want to group tokens when computing the metrics
		_UpperCamelCase   :		Tuple			=						processor.batch_decode(pred.label_ids							,       group_tokens=UpperCAmelCase_	)

		_UpperCamelCase   :		List[Any]			=						wer_metric.compute(predictions=UpperCAmelCase_							,       references=UpperCAmelCase_	)

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	# Data collator
	_UpperCamelCase   :		Union[str, Any]			=						DataCollatorCTCWithPadding(processor=UpperCAmelCase_							,       padding=UpperCAmelCase_	)

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

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

		_UpperCamelCase   :		str			=						trainer.train(resume_from_checkpoint=UpperCAmelCase_	)
		trainer.save_model()

		_UpperCamelCase   :		str			=						train_result.metrics
		_UpperCamelCase   :		Dict			=						(
		    data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase_	)
		)
		_UpperCamelCase   :		Tuple			=						min(UpperCAmelCase_							,       len(UpperCAmelCase_	)	)

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

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

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

	return results


if __name__ == "__main__":
							main()







import inspect
import unittest

from transformers import BitConfig
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_backbone_common import BackboneTesterMixin
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 torch import nn

							from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel
							from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image







class 	lowercase    :


		"""simple docstring"""




		def __init__(				self	,       __snake_case	,       __snake_case=3	,       __snake_case=32	,       __snake_case=3	,       __snake_case=10	,       __snake_case=[8, 16, 32, 64]	,       __snake_case=[1, 1, 2, 1]	,       __snake_case=True	,       __snake_case=True	,       __snake_case="relu"	,       __snake_case=3	,       __snake_case=None	,       __snake_case=["stage2", "stage3", "stage4"]	,       __snake_case=[2, 3, 4]	,       __snake_case=1	,       ):
			_UpperCamelCase   :		List[Any]			=						parent
			_UpperCamelCase   :		Dict			=						batch_size
			_UpperCamelCase   :		Optional[int]			=						image_size
			_UpperCamelCase   :		str			=						num_channels
			_UpperCamelCase   :		Optional[Any]			=						embeddings_size
			_UpperCamelCase   :		Tuple			=						hidden_sizes
			_UpperCamelCase   :		Dict			=						depths
			_UpperCamelCase   :		str			=						is_training
			_UpperCamelCase   :		Optional[int]			=						use_labels
			_UpperCamelCase   :		str			=						hidden_act
			_UpperCamelCase   :		Optional[int]			=						num_labels
			_UpperCamelCase   :		Optional[int]			=						scope
			_UpperCamelCase   :		Tuple			=						len(__snake_case)
			_UpperCamelCase   :		Dict			=						out_features
			_UpperCamelCase   :		Union[str, Any]			=						out_indices
			_UpperCamelCase   :		int			=						num_groups


		def 		A__					(				self):
			_UpperCamelCase   :		Tuple			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

			_UpperCamelCase   :		str			=						None
			if self.use_labels:
				_UpperCamelCase   :		Optional[int]			=						ids_tensor([self.batch_size]	,       self.num_labels)

			_UpperCamelCase   :		str			=						self.get_config()

			return config, pixel_values, labels


		def 		A__					(				self):
			return BitConfig(
			    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	,       out_features=self.out_features	,       out_indices=self.out_indices	,       num_groups=self.num_groups	,       )


		def 		A__					(				self	,       __snake_case	,       __snake_case	,       __snake_case):
			_UpperCamelCase   :		str			=						BitModel(config=__snake_case)
			model.to(__snake_case)
			model.eval()
			_UpperCamelCase   :		Optional[Any]			=						model(__snake_case)
			self.parent.assertEqual(
			    result.last_hidden_state.shape	,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,       )


		def 		A__					(				self	,       __snake_case	,       __snake_case	,       __snake_case):
			_UpperCamelCase   :		Dict			=						self.num_labels
			_UpperCamelCase   :		Dict			=						BitForImageClassification(__snake_case)
			model.to(__snake_case)
			model.eval()
			_UpperCamelCase   :		Dict			=						model(__snake_case	,       labels=__snake_case)
			self.parent.assertEqual(result.logits.shape	,       (self.batch_size, self.num_labels))


		def 		A__					(				self	,       __snake_case	,       __snake_case	,       __snake_case):
			_UpperCamelCase   :		Optional[Any]			=						BitBackbone(config=__snake_case)
			model.to(__snake_case)
			model.eval()
			_UpperCamelCase   :		List[Any]			=						model(__snake_case)

			# verify feature maps
			self.parent.assertEqual(len(result.feature_maps)	,       len(config.out_features))
			self.parent.assertListEqual(list(result.feature_maps[0].shape)	,       [self.batch_size, self.hidden_sizes[1], 4, 4])

			# verify channels
			self.parent.assertEqual(len(model.channels)	,       len(config.out_features))
			self.parent.assertListEqual(model.channels	,       config.hidden_sizes[1:])

			# verify backbone works with out_features=None
			_UpperCamelCase   :		Any			=						None
			_UpperCamelCase   :		str			=						BitBackbone(config=__snake_case)
			model.to(__snake_case)
			model.eval()
			_UpperCamelCase   :		Any			=						model(__snake_case)

			# verify feature maps
			self.parent.assertEqual(len(result.feature_maps)	,       1)
			self.parent.assertListEqual(list(result.feature_maps[0].shape)	,       [self.batch_size, self.hidden_sizes[-1], 1, 1])

			# verify channels
			self.parent.assertEqual(len(model.channels)	,       1)
			self.parent.assertListEqual(model.channels	,       [config.hidden_sizes[-1]])






		def 		A__					(				self):
			_UpperCamelCase   :		Optional[int]			=						self.prepare_config_and_inputs()
			_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase   :		int			=						config_and_inputs
			_UpperCamelCase   :		int			=						{'pixel_values': pixel_values}
			return config, inputs_dict







@require_torch
class 	lowercase    (				_lowercase    ,							_lowercase    ,							unittest.TestCase							):


		"""simple docstring"""




		a__					       =  (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
		a__					       =  (
		    {"feature-extraction": BitModel, "image-classification": BitForImageClassification}
		    if is_torch_available()
		    else {}
		)

		a__					       =  False
		a__					       =  False
		a__					       =  False
		a__					       =  False
		a__					       =  False


		def 		A__					(				self):
			_UpperCamelCase   :		Dict			=						BitModelTester(self)
			_UpperCamelCase   :		Optional[Any]			=						ConfigTester(self	,       config_class=__snake_case	,       has_text_modality=__snake_case)


		def 		A__					(				self):
			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 		A__					(				self):
			return


		@unittest.skip(reason='Bit does not output attentions')
		def 		A__					(				self):
			pass


		@unittest.skip(reason='Bit does not use inputs_embeds')
		def 		A__					(				self):
			pass


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


		def 		A__					(				self):
			_UpperCamelCase	,		_UpperCamelCase   :		List[Any]			=						self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				_UpperCamelCase   :		int			=						model_class(__snake_case)
				_UpperCamelCase   :		List[Any]			=						inspect.signature(model.forward)
				# signature.parameters is an OrderedDict => so arg_names order is deterministic
				_UpperCamelCase   :		Optional[int]			=						[*signature.parameters.keys()]

				_UpperCamelCase   :		List[Any]			=						['pixel_values']
				self.assertListEqual(arg_names[:1]	,       __snake_case)


		def 		A__					(				self):
			_UpperCamelCase   :		Union[str, Any]			=						self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*__snake_case)


		def 		A__					(				self):
			_UpperCamelCase   :		Tuple			=						self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_backbone(*__snake_case)


		def 		A__					(				self):
			_UpperCamelCase	,		_UpperCamelCase   :		Optional[int]			=						self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				_UpperCamelCase   :		Union[str, Any]			=						model_class(config=__snake_case)
				for name, module in model.named_modules():
					if isinstance(__snake_case	,       (nn.BatchNormad, nn.GroupNorm)):
						self.assertTrue(
						    torch.all(module.weight == 1)	,       msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''	,       )
						self.assertTrue(
						    torch.all(module.bias == 0)	,       msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''	,       )


		def 		A__					(				self):
			def check_hidden_states_output(__snake_case	,       __snake_case	,       __snake_case):
				_UpperCamelCase   :		str			=						model_class(__snake_case)
				model.to(__snake_case)
				model.eval()

				with torch.no_grad():
					_UpperCamelCase   :		Union[str, Any]			=						model(**self._prepare_for_class(__snake_case	,       __snake_case))

				_UpperCamelCase   :		List[Any]			=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

				_UpperCamelCase   :		str			=						self.model_tester.num_stages
				self.assertEqual(len(__snake_case)	,       expected_num_stages + 1)

				# Bit's feature maps are of shape (batch_size, num_channels, height, width)
				self.assertListEqual(
				    list(hidden_states[0].shape[-2:])	,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4]	,       )

			_UpperCamelCase	,		_UpperCamelCase   :		int			=						self.model_tester.prepare_config_and_inputs_for_common()
			_UpperCamelCase   :		List[str]			=						['preactivation', 'bottleneck']
			for model_class in self.all_model_classes:
				for layer_type in layers_type:
					_UpperCamelCase   :		Any			=						layer_type
					_UpperCamelCase   :		Tuple			=						True
					check_hidden_states_output(__snake_case	,       __snake_case	,       __snake_case)

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

					check_hidden_states_output(__snake_case	,       __snake_case	,       __snake_case)


		@unittest.skip(reason='Bit does not use feedforward chunking')
		def 		A__					(				self):
			pass


		def 		A__					(				self):
			_UpperCamelCase   :		Union[str, Any]			=						self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*__snake_case)






		@slow
		def 		A__					(				self):
			for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				_UpperCamelCase   :		Optional[Any]			=						BitModel.from_pretrained(__snake_case)
				self.assertIsNotNone(__snake_case)






def 					lowerCamelCase_     (							)						->				Optional[int]:




	'''simple docstring'''




	_UpperCamelCase   :		List[Any]			=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
	return image







@require_torch
@require_vision
class 	lowercase    (				unittest.TestCase							):


		"""simple docstring"""




		@cached_property
		def 		A__					(				self):
			return (
			    BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None
			)






		@slow
		def 		A__					(				self):
			_UpperCamelCase   :		Optional[Any]			=						BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(__snake_case)

			_UpperCamelCase   :		str			=						self.default_image_processor
			_UpperCamelCase   :		List[str]			=						prepare_img()
			_UpperCamelCase   :		int			=						image_processor(images=__snake_case	,       return_tensors='pt').to(__snake_case)

			# forward pass
			with torch.no_grad():
				_UpperCamelCase   :		Any			=						model(**__snake_case)

			# verify the logits
			_UpperCamelCase   :		Dict			=						torch.Size((1, 10_00))
			self.assertEqual(outputs.logits.shape	,       __snake_case)

			_UpperCamelCase   :		Optional[int]			=						torch.tensor([[-0.6_5_2_6, -0.5_2_6_3, -1.4_3_9_8]]).to(__snake_case)

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







@require_torch
class 	lowercase    (				_lowercase    ,							unittest.TestCase							):


		"""simple docstring"""




		a__					       =  (BitBackbone,) if is_torch_available() else ()
		a__					       =  BitConfig

		a__					       =  False


		def 		A__					(				self):
			_UpperCamelCase   :		List[str]			=						BitModelTester(self)




