





import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

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


if is_torch_available():
	import torch

	from transformers import (
	    DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
	    DistilBertForMaskedLM,
	    DistilBertForMultipleChoice,
	    DistilBertForQuestionAnswering,
	    DistilBertForSequenceClassification,
	    DistilBertForTokenClassification,
	    DistilBertModel,
	)



class    __lowerCAmelCase			(     _a	):






			def __init__(self   ,				__magic_name__   ,				__magic_name__=13   ,				__magic_name__=7   ,				__magic_name__=True   ,				__magic_name__=True   ,				__magic_name__=False   ,				__magic_name__=True   ,				__magic_name__=99   ,				__magic_name__=32   ,				__magic_name__=5   ,				__magic_name__=4   ,				__magic_name__=37   ,				__magic_name__="gelu"   ,				__magic_name__=0.1   ,				__magic_name__=0.1   ,				__magic_name__=512   ,				__magic_name__=16   ,				__magic_name__=2   ,				__magic_name__=0.02   ,				__magic_name__=3   ,				__magic_name__=4   ,				__magic_name__=None   ,				)	->  Dict:


							'''simple docstring'''



							snake_case_		:       List[str]           =    parent
							snake_case_		:       List[Any]           =    batch_size
							snake_case_		:       List[Any]           =    seq_length
							snake_case_		:       List[Any]           =    is_training
							snake_case_		:       Optional[Any]           =    use_input_mask
							snake_case_		:       str           =    use_token_type_ids
							snake_case_		:       List[str]           =    use_labels
							snake_case_		:       int           =    vocab_size
							snake_case_		:       int           =    hidden_size
							snake_case_		:       Optional[Any]           =    num_hidden_layers
							snake_case_		:       Union[str, Any]           =    num_attention_heads
							snake_case_		:       Tuple           =    intermediate_size
							snake_case_		:       int           =    hidden_act
							snake_case_		:       Tuple           =    hidden_dropout_prob
							snake_case_		:       Dict           =    attention_probs_dropout_prob
							snake_case_		:       List[str]           =    max_position_embeddings
							snake_case_		:       List[Any]           =    type_vocab_size
							snake_case_		:       List[str]           =    type_sequence_label_size
							snake_case_		:       Union[str, Any]           =    initializer_range
							snake_case_		:       List[Any]           =    num_labels
							snake_case_		:       Optional[int]           =    num_choices
							snake_case_		:       Any           =    scope






			def      lowerCamelCase    (self       )	->  str:


							'''simple docstring'''



							snake_case_		:       Optional[int]           =    ids_tensor([self.batch_size, self.seq_length]   ,				self.vocab_size       )

							snake_case_		:       List[Any]           =    None
							if self.use_input_mask:
											snake_case_		:       Optional[Any]           =    random_attention_mask([self.batch_size, self.seq_length]       )

							snake_case_		:       int           =    None
							snake_case_		:       Optional[Any]           =    None
							snake_case_		:       Tuple           =    None
							if self.use_labels:
											snake_case_		:       Optional[int]           =    ids_tensor([self.batch_size]   ,				self.type_sequence_label_size       )
											snake_case_		:       Dict           =    ids_tensor([self.batch_size, self.seq_length]   ,				self.num_labels       )
											snake_case_		:       Dict           =    ids_tensor([self.batch_size]   ,				self.num_choices       )

							snake_case_		:       Dict           =    self.get_config()

							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






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


							'''simple docstring'''



							return DistilBertConfig(
							    vocab_size=self.vocab_size   ,				dim=self.hidden_size   ,				n_layers=self.num_hidden_layers   ,				n_heads=self.num_attention_heads   ,				hidden_dim=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				dropout=self.hidden_dropout_prob   ,				attention_dropout=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				initializer_range=self.initializer_range   ,				)






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Optional[Any]:


							'''simple docstring'''



							snake_case_		:       str           =    DistilBertModel(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       List[Any]           =    model(__magic_name__   ,				__magic_name__       )
							snake_case_		:       List[Any]           =    model(__magic_name__       )
							self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Any:


							'''simple docstring'''



							snake_case_		:       str           =    DistilBertForMaskedLM(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       str           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.vocab_size)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  int:


							'''simple docstring'''



							snake_case_		:       Optional[int]           =    DistilBertForQuestionAnswering(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Union[str, Any]           =    model(
							    __magic_name__   ,				attention_mask=__magic_name__   ,				start_positions=__magic_name__   ,				end_positions=__magic_name__       )
							self.parent.assertEqual(result.start_logits.shape   ,				(self.batch_size, self.seq_length)       )
							self.parent.assertEqual(result.end_logits.shape   ,				(self.batch_size, self.seq_length)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Any:


							'''simple docstring'''



							snake_case_		:       str           =    self.num_labels
							snake_case_		:       str           =    DistilBertForSequenceClassification(__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Optional[int]           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  str:


							'''simple docstring'''



							snake_case_		:       Dict           =    self.num_labels
							snake_case_		:       List[Any]           =    DistilBertForTokenClassification(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()

							snake_case_		:       Optional[Any]           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.num_labels)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  List[str]:


							'''simple docstring'''



							snake_case_		:       Any           =    self.num_choices
							snake_case_		:       List[Any]           =    DistilBertForMultipleChoice(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       int           =    input_ids.unsqueeze(1       ).expand(-1   ,				self.num_choices   ,				-1       ).contiguous()
							snake_case_		:       Optional[int]           =    input_mask.unsqueeze(1       ).expand(-1   ,				self.num_choices   ,				-1       ).contiguous()
							snake_case_		:       Tuple           =    model(
							    __magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__   ,				)
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_choices)       )






			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							snake_case_		:       Dict           =    self.prepare_config_and_inputs()
							((snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_))		:       Union[str, Any]           =    config_and_inputs
							snake_case_		:       Optional[int]           =    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
							return config, inputs_dict




@require_torch
class    __lowerCAmelCase			(     _a,	_a,	unittest.TestCase	):
			lowerCamelCase_	:	Optional[int]			     = (
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			lowerCamelCase_	:	str			     = (
			    {
			        '''feature-extraction''': DistilBertModel,
			        '''fill-mask''': DistilBertForMaskedLM,
			        '''question-answering''': DistilBertForQuestionAnswering,
			        '''text-classification''': DistilBertForSequenceClassification,
			        '''token-classification''': DistilBertForTokenClassification,
			        '''zero-shot''': DistilBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase_	:	Optional[Any]			     = True
			lowerCamelCase_	:	List[Any]			     = True
			lowerCamelCase_	:	int			     = True
			lowerCamelCase_	:	str			     = True






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


							'''simple docstring'''



							snake_case_		:       int           =    DistilBertModelTester(self       )
							snake_case_		:       List[str]           =    ConfigTester(self   ,				config_class=__magic_name__   ,				dim=37       )






			def      lowerCamelCase    (self       )	->  int:


							'''simple docstring'''



							self.config_tester.run_common_tests()






			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							snake_case_		:       Union[str, Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_model(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  Any:


							'''simple docstring'''



							snake_case_		:       List[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_masked_lm(*__magic_name__       )






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


							'''simple docstring'''



							snake_case_		:       int           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_question_answering(*__magic_name__       )






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


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_sequence_classification(*__magic_name__       )






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


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_token_classification(*__magic_name__       )






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


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_multiple_choice(*__magic_name__       )






			@slow
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:       Tuple           =    DistilBertModel.from_pretrained(__magic_name__       )
											self.assertIsNotNone(__magic_name__       )






			@slow
			@require_torch_gpu
			def      lowerCamelCase    (self       )	->  Dict:


							'''simple docstring'''



							snake_case_     ,				snake_case_		:       Optional[int]           =    self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
											# BertForMultipleChoice behaves incorrectly in JIT environments.
											if model_class == DistilBertForMultipleChoice:
															return

											snake_case_		:       List[str]           =    True
											snake_case_		:       Tuple           =    model_class(config=__magic_name__       )

											snake_case_		:       Tuple           =    self._prepare_for_class(__magic_name__   ,				__magic_name__       )
											snake_case_		:       List[str]           =    torch.jit.trace(
											    __magic_name__   ,				(inputs_dict['''input_ids'''].to('''cpu'''       ), inputs_dict['''attention_mask'''].to('''cpu'''       ))       )

											with tempfile.TemporaryDirectory() as tmp:
															torch.jit.save(__magic_name__   ,				os.path.join(__magic_name__   ,				'''traced_model.pt'''       )       )
															snake_case_		:       Union[str, Any]           =    torch.jit.load(os.path.join(__magic_name__   ,				'''traced_model.pt'''       )   ,				map_location=__magic_name__       )
															loaded(inputs_dict['''input_ids'''].to(__magic_name__       )   ,				inputs_dict['''attention_mask'''].to(__magic_name__       )       )




@require_torch
class    __lowerCAmelCase			(     unittest.TestCase	):






			@slow
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							snake_case_		:       Tuple           =    DistilBertModel.from_pretrained('''distilbert-base-uncased'''       )
							snake_case_		:       List[Any]           =    torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]       )
							snake_case_		:       Union[str, Any]           =    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
							with torch.no_grad():
											snake_case_		:       int           =    model(__magic_name__   ,				attention_mask=__magic_name__       )[0]
							snake_case_		:       int           =    torch.Size((1, 11, 768)       )
							self.assertEqual(output.shape   ,				__magic_name__       )
							snake_case_		:       Union[str, Any]           =    torch.tensor(
							    [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]]       )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]   ,				__magic_name__   ,				atol=1e-4       )       )




import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case__				:	Union[str, Any]					       =					logging.get_logger(__name__)

snake_case__				:	Tuple					       =					{
    'microsoft/unispeech-sat-base-100h-libri-ft': (
        'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}





class   SCREAMING_SNAKE_CASE_			(a__						):




       '''simple docstring'''



       _a   							=							"unispeech-sat"



       def __init__(						self				:				List[str]		,				__a				:				Dict=32		,				__a				:				int=768		,				__a				:				int=12		,				__a				:				Tuple=12		,				__a				:				Optional[int]=3_072		,				__a				:				int="gelu"		,				__a				:				Optional[int]=0.1		,				__a				:				Union[str, Any]=0.1		,				__a				:				Any=0.1		,				__a				:				str=0.0		,				__a				:				List[str]=0.0		,				__a				:				int=0.1		,				__a				:				List[Any]=0.1		,				__a				:				Tuple=0.02		,				__a				:				str=1e-5		,				__a				:				Optional[int]="group"		,				__a				:				Any="gelu"		,				__a				:				Optional[Any]=(512, 512, 512, 512, 512, 512, 512)		,				__a				:				Optional[Any]=(5, 2, 2, 2, 2, 2, 2)		,				__a				:				List[Any]=(10, 3, 3, 3, 3, 2, 2)		,				__a				:				Optional[Any]=False		,				__a				:				Optional[int]=128		,				__a				:				Dict=16		,				__a				:				str=False		,				__a				:				List[Any]=True		,				__a				:				Tuple=0.05		,				__a				:				str=10		,				__a				:				Any=2		,				__a				:				Any=0.0		,				__a				:				List[Any]=10		,				__a				:				str=0		,				__a				:				str=320		,				__a				:				int=2		,				__a				:				Optional[Any]=0.1		,				__a				:				Optional[int]=100		,				__a				:				Any=256		,				__a				:				Optional[int]=256		,				__a				:				int=0.1		,				__a				:				Tuple="mean"		,				__a				:				List[str]=False		,				__a				:				Optional[Any]=False		,				__a				:				List[Any]=256		,				__a				:				Dict=(512, 512, 512, 512, 1_500)		,				__a				:				int=(5, 3, 3, 1, 1)		,				__a				:				str=(1, 2, 3, 1, 1)		,				__a				:				str=512		,				__a				:				str=0		,				__a				:				List[Any]=1		,				__a				:				Optional[Any]=2		,				__a				:				Optional[int]=504		,				**__a				:				Tuple		,				)					->Dict:
          super().__init__(**__a		,				pad_token_id=__a		,				bos_token_id=__a		,				eos_token_id=__a							)
          lowerCamelCase_						:   Any		= hidden_size
          lowerCamelCase_						:   Optional[int]		= feat_extract_norm
          lowerCamelCase_						:   Dict		= feat_extract_activation
          lowerCamelCase_						:   List[Any]		= list(__a							)
          lowerCamelCase_						:   Any		= list(__a							)
          lowerCamelCase_						:   List[Any]		= list(__a							)
          lowerCamelCase_						:   str		= conv_bias
          lowerCamelCase_						:   int		= num_conv_pos_embeddings
          lowerCamelCase_						:   List[Any]		= num_conv_pos_embedding_groups
          lowerCamelCase_						:   str		= len(self.conv_dim							)
          lowerCamelCase_						:   Any		= num_hidden_layers
          lowerCamelCase_						:   List[str]		= intermediate_size
          lowerCamelCase_						:   Tuple		= hidden_act
          lowerCamelCase_						:   List[str]		= num_attention_heads
          lowerCamelCase_						:   Any		= hidden_dropout
          lowerCamelCase_						:   Optional[int]		= attention_dropout
          lowerCamelCase_						:   Tuple		= activation_dropout
          lowerCamelCase_						:   str		= feat_proj_dropout
          lowerCamelCase_						:   Any		= final_dropout
          lowerCamelCase_						:   Optional[Any]		= layerdrop
          lowerCamelCase_						:   str		= layer_norm_eps
          lowerCamelCase_						:   str		= initializer_range
          lowerCamelCase_						:   Optional[Any]		= vocab_size
          lowerCamelCase_						:   Optional[int]		= num_clusters
          lowerCamelCase_						:   List[Any]		= do_stable_layer_norm
          lowerCamelCase_						:   Tuple		= use_weighted_layer_sum

          if (
              (len(self.conv_stride							) != self.num_feat_extract_layers)
              or (len(self.conv_kernel							) != self.num_feat_extract_layers)
              or (len(self.conv_dim							) != self.num_feat_extract_layers)
          ):
             raise ValueError(
                 """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                 """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                 F''' {len(self.conv_dim							)}`, `len(config.conv_stride) = {len(self.conv_stride							)}`,'''
                 F''' `len(config.conv_kernel) = {len(self.conv_kernel							)}`.'''							)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          lowerCamelCase_						:   List[str]		= apply_spec_augment
          lowerCamelCase_						:   str		= mask_time_prob
          lowerCamelCase_						:   List[Any]		= mask_time_length
          lowerCamelCase_						:   Optional[int]		= mask_time_min_masks
          lowerCamelCase_						:   List[Any]		= mask_feature_prob
          lowerCamelCase_						:   Optional[int]		= mask_feature_length
          lowerCamelCase_						:   Dict		= mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          lowerCamelCase_						:   Dict		= num_codevectors_per_group
          lowerCamelCase_						:   List[str]		= num_codevector_groups
          lowerCamelCase_						:   Union[str, Any]		= contrastive_logits_temperature
          lowerCamelCase_						:   Optional[int]		= feat_quantizer_dropout
          lowerCamelCase_						:   List[Any]		= num_negatives
          lowerCamelCase_						:   Optional[int]		= codevector_dim
          lowerCamelCase_						:   str		= proj_codevector_dim
          lowerCamelCase_						:   List[Any]		= diversity_loss_weight

          # ctc loss
          lowerCamelCase_						:   Optional[int]		= ctc_loss_reduction
          lowerCamelCase_						:   int		= ctc_zero_infinity

          # SequenceClassification-specific parameter. Feel free to ignore for other classes.
          lowerCamelCase_						:   Dict		= classifier_proj_size

          # XVector-specific parameters. Feel free to ignore for other classes.
          lowerCamelCase_						:   List[Any]		= list(__a							)
          lowerCamelCase_						:   Any		= list(__a							)
          lowerCamelCase_						:   List[Any]		= list(__a							)
          lowerCamelCase_						:   Optional[int]		= xvector_output_dim




       @property
       def 				_lowerCAmelCase							(						self				:				int							)					->Optional[Any]:
          return functools.reduce(operator.mul		,				self.conv_stride		,				1							)





