


import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np
import torch

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


A			:						Dict        =  logging.get_logger(__name__)



class 				A       (			_lowerCAmelCase				):
					'''simple docstring'''






					A__     =					['''input_features''', '''is_longer''']

					def __init__(self       :		str ,   _UpperCAmelCase       :		Optional[Any]=64 ,   _UpperCAmelCase       :		List[Any]=4_8000 ,   _UpperCAmelCase       :		Any=480 ,   _UpperCAmelCase       :		Dict=10 ,   _UpperCAmelCase       :		Optional[Any]=1024 ,   _UpperCAmelCase       :		List[str]=0.0 ,   _UpperCAmelCase       :		Dict=False ,   _UpperCAmelCase       :		str = 0 ,   _UpperCAmelCase       :		Any = 1_4000 ,   _UpperCAmelCase       :		int = None ,   _UpperCAmelCase       :		Tuple = "fusion" ,   _UpperCAmelCase       :		Tuple = "repeatpad" ,   **_UpperCAmelCase       :		List[Any] ,   )		->  Union[str, Any]:




							"""simple docstring"""


							super().__init__(
							    feature_size=SCREAMING_SNAKE_CASE_ ,   sampling_rate=SCREAMING_SNAKE_CASE_ ,   padding_value=SCREAMING_SNAKE_CASE_ ,   return_attention_mask=SCREAMING_SNAKE_CASE_ ,   **SCREAMING_SNAKE_CASE_ ,   )
							lowercase__	     =						top_db
							lowercase__	     =						truncation
							lowercase__	     =						padding
							lowercase__	     =						fft_window_size
							lowercase__	     =						(fft_window_size >> 1) + 1
							lowercase__	     =						hop_length
							lowercase__	     =						max_length_s
							lowercase__	     =						max_length_s * sampling_rate
							lowercase__	     =						sampling_rate
							lowercase__	     =						frequency_min
							lowercase__	     =						frequency_max
							lowercase__	     =						mel_filter_bank(
							    num_frequency_bins=self.nb_frequency_bins ,   num_mel_filters=SCREAMING_SNAKE_CASE_ ,   min_frequency=SCREAMING_SNAKE_CASE_ ,   max_frequency=SCREAMING_SNAKE_CASE_ ,   sampling_rate=SCREAMING_SNAKE_CASE_ ,   norm=SCREAMING_SNAKE_CASE_ ,   mel_scale="""htk""" ,   )
							lowercase__	     =						mel_filter_bank(
							    num_frequency_bins=self.nb_frequency_bins ,   num_mel_filters=SCREAMING_SNAKE_CASE_ ,   min_frequency=SCREAMING_SNAKE_CASE_ ,   max_frequency=SCREAMING_SNAKE_CASE_ ,   sampling_rate=SCREAMING_SNAKE_CASE_ ,   norm="""slaney""" ,   mel_scale="""slaney""" ,   )

					def     lowerCamelCase__	(self       :		Optional[Any]						)		->  Dict[str, Any]:




							"""simple docstring"""


							lowercase__	     =						copy.deepcopy(self.__dict__						)
							lowercase__	     =						self.__class__.__name__
							if "mel_filters" in output:
									del output["mel_filters"]
							if "mel_filters_slaney" in output:
									del output["mel_filters_slaney"]
							return output

					def     lowerCamelCase__	(self       :		List[str] ,   _UpperCAmelCase       :		List[str] ,   _UpperCAmelCase       :		Optional[Any] = None						)		->  np.ndarray:




							"""simple docstring"""


							lowercase__	     =						spectrogram(
							    SCREAMING_SNAKE_CASE_ ,   window_function(self.fft_window_size ,   """hann"""						) ,   frame_length=self.fft_window_size ,   hop_length=self.hop_length ,   power=2.0 ,   mel_filters=SCREAMING_SNAKE_CASE_ ,   log_mel="""dB""" ,   )
							return log_mel_spectrogram.T

					def     lowerCamelCase__	(self       :		List[Any] ,   _UpperCAmelCase       :		Optional[int] ,   _UpperCAmelCase       :		List[str] ,   _UpperCAmelCase       :		Optional[Any]						)		->  Dict:




							"""simple docstring"""


							lowercase__	     =						np.array_split(list(range(0 ,   total_frames - chunk_frames + 1						)						) ,   3						)
							if len(ranges[1]						) == 0:
									# if the audio is too short, we just use the first chunk
									lowercase__	     =						[0]
							if len(ranges[2]						) == 0:
									# if the audio is too short, we just use the first chunk
									lowercase__	     =						[0]
							# randomly choose index for each part
							lowercase__	     =						np.random.choice(ranges[0]						)
							lowercase__	     =						np.random.choice(ranges[1]						)
							lowercase__	     =						np.random.choice(ranges[2]						)

							lowercase__	     =						mel[idx_front : idx_front + chunk_frames, :]
							lowercase__	     =						mel[idx_middle : idx_middle + chunk_frames, :]
							lowercase__	     =						mel[idx_back : idx_back + chunk_frames, :]

							lowercase__	     =						torch.tensor(mel[None, None, :]						)
							lowercase__	     =						torch.nn.functional.interpolate(
							    SCREAMING_SNAKE_CASE_ ,   size=[chunk_frames, 64] ,   mode="""bilinear""" ,   align_corners=SCREAMING_SNAKE_CASE_						)
							lowercase__	     =						mel_shrink[0][0].numpy()
							lowercase__	     =						np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] ,   axis=0						)
							return mel_fusion

					def     lowerCamelCase__	(self       :		int ,   _UpperCAmelCase       :		int ,   _UpperCAmelCase       :		int ,   _UpperCAmelCase       :		Optional[int] ,   _UpperCAmelCase       :		Optional[int]						)		->  np.array:




							"""simple docstring"""


							if waveform.shape[0] > max_length:
									if truncation == "rand_trunc":
											lowercase__	     =						True
											# random crop to max_length (for compatibility) -> this should be handled by self.pad
											lowercase__	     =						len(SCREAMING_SNAKE_CASE_						) - max_length
											lowercase__	     =						np.random.randint(0 ,   overflow + 1						)
											lowercase__	     =						waveform[idx : idx + max_length]
											lowercase__	     =						self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ ,   self.mel_filters_slaney						)[None, :]
									elif truncation == "fusion":
											lowercase__	     =						self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ ,   self.mel_filters						)
											lowercase__	     =						max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
											lowercase__	     =						mel.shape[0]
											if chunk_frames == total_frames:
													# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
													# In this case, we just use the whole audio.
													lowercase__	     =						np.stack([mel, mel, mel, mel] ,   axis=0						)
													lowercase__	     =						False
											else:
													lowercase__	     =						self._random_mel_fusion(SCREAMING_SNAKE_CASE_ ,   SCREAMING_SNAKE_CASE_ ,   SCREAMING_SNAKE_CASE_						)
													lowercase__	     =						True
									else:
											raise NotImplementedError(f'''data_truncating {truncation} not implemented'''						)

							else:
									lowercase__	     =						False
									# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
									if waveform.shape[0] < max_length:
											if padding == "repeat":
													lowercase__	     =						int(max_length / len(SCREAMING_SNAKE_CASE_						)						)
													lowercase__	     =						np.stack(np.tile(SCREAMING_SNAKE_CASE_ ,   n_repeat + 1						)						)[:max_length]
											if padding == "repeatpad":
													lowercase__	     =						int(max_length / len(SCREAMING_SNAKE_CASE_						)						)
													lowercase__	     =						np.stack(np.tile(SCREAMING_SNAKE_CASE_ ,   SCREAMING_SNAKE_CASE_						)						)
											lowercase__	     =						np.pad(SCREAMING_SNAKE_CASE_ ,   (0, max_length - waveform.shape[0]) ,   mode="""constant""" ,   constant_values=0						)

									if truncation == "fusion":
											lowercase__	     =						self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ ,   self.mel_filters						)
											lowercase__	     =						np.stack([input_mel, input_mel, input_mel, input_mel] ,   axis=0						)
									else:
											lowercase__	     =						self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ ,   self.mel_filters_slaney						)[None, :]

							return input_mel, longer


					def __call__(self       :		int ,   _UpperCAmelCase       :		int ,   _UpperCAmelCase       :		Optional[Any] = None ,   _UpperCAmelCase       :		str = None ,   _UpperCAmelCase       :		int = None ,   _UpperCAmelCase       :		List[str] = None ,   _UpperCAmelCase       :		Optional[Any] = None ,   **_UpperCAmelCase       :		Any ,   )		->  BatchFeature:




							"""simple docstring"""


							lowercase__	     =						truncation if truncation is not None else self.truncation
							lowercase__	     =						padding if padding else self.padding

							if sampling_rate is not None:
									if sampling_rate != self.sampling_rate:
											raise ValueError(
											    f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
											    f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
											    f''' was sampled with {self.sampling_rate} and not {sampling_rate}.'''						)
							else:
									logger.warning(
									    """It is strongly recommended to pass the `sampling_rate` argument to this function. """
									    """Failing to do so can result in silent errors that might be hard to debug."""						)

							lowercase__	     =						isinstance(SCREAMING_SNAKE_CASE_ ,   np.ndarray						) and len(raw_speech.shape						) > 1
							if is_batched_numpy and len(raw_speech.shape						) > 2:
									raise ValueError(f'''Only mono-channel audio is supported for input to {self}'''						)
							lowercase__	     =						is_batched_numpy or (
							    isinstance(SCREAMING_SNAKE_CASE_ ,   (list, tuple)						) and (isinstance(raw_speech[0] ,   (np.ndarray, tuple, list)						))
							)

							if is_batched:
									lowercase__	     =						[np.asarray(SCREAMING_SNAKE_CASE_ ,   dtype=np.floataa						) for speech in raw_speech]
							elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ ,   np.ndarray						):
									lowercase__	     =						np.asarray(SCREAMING_SNAKE_CASE_ ,   dtype=np.floataa						)
							elif isinstance(SCREAMING_SNAKE_CASE_ ,   np.ndarray						) and raw_speech.dtype is np.dtype(np.floataa						):
									lowercase__	     =						raw_speech.astype(np.floataa						)

							# always return batch
							if not is_batched:
									lowercase__	     =						[np.asarray(SCREAMING_SNAKE_CASE_						)]

							# convert to mel spectrogram, truncate and pad if needed.
							lowercase__	     =						[
							    self._get_input_mel(SCREAMING_SNAKE_CASE_ ,   max_length if max_length else self.nb_max_samples ,   SCREAMING_SNAKE_CASE_ ,   SCREAMING_SNAKE_CASE_						)
							    for waveform in raw_speech
							]

							lowercase__	     =						[]
							lowercase__	     =						[]
							for mel, longer in padded_inputs:
									input_mel.append(SCREAMING_SNAKE_CASE_						)
									is_longer.append(SCREAMING_SNAKE_CASE_						)

							if truncation == "fusion" and sum(SCREAMING_SNAKE_CASE_						) == 0:
									# if no audio is longer than 10s, then randomly select one audio to be longer
									lowercase__	     =						np.random.randint(0 ,   len(SCREAMING_SNAKE_CASE_						)						)
									lowercase__	     =						True

							if isinstance(input_mel[0] ,   SCREAMING_SNAKE_CASE_						):
									lowercase__	     =						[np.asarray(SCREAMING_SNAKE_CASE_ ,   dtype=np.floataa						) for feature in input_mel]

							# is_longer is a list of bool
							lowercase__	     =						[[longer] for longer in is_longer]

							lowercase__	     =						{"""input_features""": input_mel, """is_longer""": is_longer}
							lowercase__	     =						BatchFeature(SCREAMING_SNAKE_CASE_						)

							if return_tensors is not None:
									lowercase__	     =						input_features.convert_to_tensors(SCREAMING_SNAKE_CASE_						)

							return input_features






import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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 (
	    MODEL_FOR_PRETRAINING_MAPPING,
	    AlbertForMaskedLM,
	    AlbertForMultipleChoice,
	    AlbertForPreTraining,
	    AlbertForQuestionAnswering,
	    AlbertForSequenceClassification,
	    AlbertForTokenClassification,
	    AlbertModel,
	)
	from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 				_a				:

			def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_=13,   SCREAMING_SNAKE_CASE_=7,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=99,   SCREAMING_SNAKE_CASE_=16,   SCREAMING_SNAKE_CASE_=36,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=37,   SCREAMING_SNAKE_CASE_="gelu",   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=512,   SCREAMING_SNAKE_CASE_=16,   SCREAMING_SNAKE_CASE_=2,   SCREAMING_SNAKE_CASE_=0.0_2,   SCREAMING_SNAKE_CASE_=3,   SCREAMING_SNAKE_CASE_=4,   SCREAMING_SNAKE_CASE_=None,   )       ->   Tuple:
						UpperCAmelCase_:		Any							      =     parent
						UpperCAmelCase_:		Union[str, Any]							      =     batch_size
						UpperCAmelCase_:		int							      =     seq_length
						UpperCAmelCase_:		Any							      =     is_training
						UpperCAmelCase_:		str							      =     use_input_mask
						UpperCAmelCase_:		Dict							      =     use_token_type_ids
						UpperCAmelCase_:		Any							      =     use_labels
						UpperCAmelCase_:		Any							      =     vocab_size
						UpperCAmelCase_:		Dict							      =     embedding_size
						UpperCAmelCase_:		Dict							      =     hidden_size
						UpperCAmelCase_:		Dict							      =     num_hidden_layers
						UpperCAmelCase_:		Dict							      =     num_hidden_groups
						UpperCAmelCase_:		int							      =     num_attention_heads
						UpperCAmelCase_:		List[str]							      =     intermediate_size
						UpperCAmelCase_:		Any							      =     hidden_act
						UpperCAmelCase_:		Dict							      =     hidden_dropout_prob
						UpperCAmelCase_:		Any							      =     attention_probs_dropout_prob
						UpperCAmelCase_:		Tuple							      =     max_position_embeddings
						UpperCAmelCase_:		Tuple							      =     type_vocab_size
						UpperCAmelCase_:		List[Any]							      =     type_sequence_label_size
						UpperCAmelCase_:		Any							      =     initializer_range
						UpperCAmelCase_:		int							      =     num_labels
						UpperCAmelCase_:		Optional[int]							      =     num_choices
						UpperCAmelCase_:		Tuple							      =     scope

			def      __snake_case       (self					)       ->   List[Any]:
						UpperCAmelCase_:		Union[str, Any]							      =     ids_tensor([self.batch_size, self.seq_length],   self.vocab_size					)

						UpperCAmelCase_:		Tuple							      =     None
						if self.use_input_mask:
									UpperCAmelCase_:		Union[str, Any]							      =     random_attention_mask([self.batch_size, self.seq_length]					)

						UpperCAmelCase_:		Dict							      =     None
						if self.use_token_type_ids:
									UpperCAmelCase_:		int							      =     ids_tensor([self.batch_size, self.seq_length],   self.type_vocab_size					)

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

						UpperCAmelCase_:		Optional[int]							      =     self.get_config()

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

			def      __snake_case       (self					)       ->   Optional[Any]:
						return AlbertConfig(
						    vocab_size=self.vocab_size,   hidden_size=self.hidden_size,   num_hidden_layers=self.num_hidden_layers,   num_attention_heads=self.num_attention_heads,   intermediate_size=self.intermediate_size,   hidden_act=self.hidden_act,   hidden_dropout_prob=self.hidden_dropout_prob,   attention_probs_dropout_prob=self.attention_probs_dropout_prob,   max_position_embeddings=self.max_position_embeddings,   type_vocab_size=self.type_vocab_size,   initializer_range=self.initializer_range,   num_hidden_groups=self.num_hidden_groups,   )

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Optional[Any]:
						UpperCAmelCase_:		int							      =     AlbertModel(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Optional[int]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[Any]							      =     model(SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Union[str, Any]							      =     model(SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size)					)
						self.parent.assertEqual(result.pooler_output.shape,   (self.batch_size, self.hidden_size)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   str:
						UpperCAmelCase_:		Any							      =     AlbertForPreTraining(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		List[Any]							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_,   sentence_order_label=SCREAMING_SNAKE_CASE_,   )
						self.parent.assertEqual(result.prediction_logits.shape,   (self.batch_size, self.seq_length, self.vocab_size)					)
						self.parent.assertEqual(result.sop_logits.shape,   (self.batch_size, config.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   List[str]:
						UpperCAmelCase_:		Optional[int]							      =     AlbertForMaskedLM(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Optional[Any]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.seq_length, self.vocab_size)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Tuple:
						UpperCAmelCase_:		Optional[Any]							      =     AlbertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Any							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   start_positions=SCREAMING_SNAKE_CASE_,   end_positions=SCREAMING_SNAKE_CASE_,   )
						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      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Any:
						UpperCAmelCase_:		Optional[Any]							      =     self.num_labels
						UpperCAmelCase_:		List[Any]							      =     AlbertForSequenceClassification(SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		str							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   List[Any]:
						UpperCAmelCase_:		List[str]							      =     self.num_labels
						UpperCAmelCase_:		Union[str, Any]							      =     AlbertForTokenClassification(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		List[str]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.seq_length, self.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Dict:
						UpperCAmelCase_:		Dict							      =     self.num_choices
						UpperCAmelCase_:		Dict							      =     AlbertForMultipleChoice(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		str							      =     input_ids.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		str							      =     token_type_ids.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		List[Any]							      =     input_mask.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		Union[str, Any]							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_,   )
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_choices)					)

			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_:		Optional[Any]							      =     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							
						):		List[str]							      =     config_and_inputs
						UpperCAmelCase_:		Tuple							      =     {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
						return config, inputs_dict







@require_torch
class 				_a				(   _lowerCAmelCase ,		_lowerCAmelCase ,		unittest.TestCase					):
			A      		=	(
			    (
			        AlbertModel,
			        AlbertForPreTraining,
			        AlbertForMaskedLM,
			        AlbertForMultipleChoice,
			        AlbertForSequenceClassification,
			        AlbertForTokenClassification,
			        AlbertForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			A      		=	(
			    {
			        '''feature-extraction''': AlbertModel,
			        '''fill-mask''': AlbertForMaskedLM,
			        '''question-answering''': AlbertForQuestionAnswering,
			        '''text-classification''': AlbertForSequenceClassification,
			        '''token-classification''': AlbertForTokenClassification,
			        '''zero-shot''': AlbertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			A      		=	True

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_=False					)       ->   Any:
						UpperCAmelCase_:		Tuple							      =     super()._prepare_for_class(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   return_labels=SCREAMING_SNAKE_CASE_					)

						if return_labels:
									if model_class in get_values(SCREAMING_SNAKE_CASE_					):
												UpperCAmelCase_:		Dict							      =     torch.zeros(
												    (self.model_tester.batch_size, self.model_tester.seq_length),   dtype=torch.long,   device=SCREAMING_SNAKE_CASE_					)
												UpperCAmelCase_:		Optional[int]							      =     torch.zeros(
												    self.model_tester.batch_size,   dtype=torch.long,   device=SCREAMING_SNAKE_CASE_					)
						return inputs_dict

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		Any							      =     AlbertModelTester(self					)
						UpperCAmelCase_:		Union[str, Any]							      =     ConfigTester(self,   config_class=SCREAMING_SNAKE_CASE_,   hidden_size=37					)

			def      __snake_case       (self					)       ->   List[Any]:
						self.config_tester.run_common_tests()

			def      __snake_case       (self					)       ->   List[Any]:
						UpperCAmelCase_:		List[Any]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Any:
						UpperCAmelCase_:		int							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		Tuple							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Optional[Any]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Any:
						UpperCAmelCase_:		List[str]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Optional[int]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Dict:
						UpperCAmelCase_:		Optional[Any]							      =     self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
									UpperCAmelCase_:		Union[str, Any]							      =     type
									self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_					)

			@slow
			def      __snake_case       (self					)       ->   List[Any]:
						for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCAmelCase_:		Dict							      =     AlbertModel.from_pretrained(SCREAMING_SNAKE_CASE_					)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE_					)







@require_torch
class 				_a				(   unittest.TestCase					):

			@slow
			def      __snake_case       (self					)       ->   Dict:
						UpperCAmelCase_:		str							      =     AlbertModel.from_pretrained("""albert-base-v2"""					)
						UpperCAmelCase_:		List[str]							      =     torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]					)
						UpperCAmelCase_:		List[str]							      =     torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
						with torch.no_grad():
									UpperCAmelCase_:		Union[str, Any]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_					)[0]
						UpperCAmelCase_:		List[str]							      =     torch.Size((1, 11, 768)					)
						self.assertEqual(output.shape,   SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Dict							      =     torch.tensor(
						    [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]					)

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






