



"""simple docstring"""






import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


__snake_case							:   Union[str, Any]      =    '\\n\n'

__snake_case							:   List[str]      =    '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'

__snake_case							:   Union[str, Any]      =    '\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        78.22\n        >>> print(round(results["perplexities"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = datasets.load_dataset("wikitext",\n        ...                                     "wikitext-2-raw-v1",\n        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!=\'\']\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        60.35\n        >>> print(round(results["perplexities"][0], 2))\n        81.12\n'



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,		_KWARGS_DESCRIPTION							)
class 			A__   (  datasets.Metric							):




	'''simple docstring'''





	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple)				->       Tuple:

				"""simple docstring"""

				return datasets.MetricInfo(
				    description=_DESCRIPTION       ,			citation=_CITATION       ,			inputs_description=_KWARGS_DESCRIPTION       ,			features=datasets.Features(
				        {
				            "input_texts": datasets.Value("string"),
				        })       ,			reference_urls=["https://huggingface.co/docs/transformers/perplexity"]       ,			)







	def 							_SCREAMING_SNAKE_CASE   (     self:		List[str]       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		List[str]       ,			_SCREAMING_SNAKE_CASE:		int = 16       ,			_SCREAMING_SNAKE_CASE:		bool = True       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=None)				->       Optional[Any]:

				"""simple docstring"""

				if device is not None:
							assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
							if device == "gpu":
										__lowerCAmelCase      :  Any												=       "cuda"
				else:
							__lowerCAmelCase      :  str												=       "cuda" if torch.cuda.is_available() else "cpu"

				__lowerCAmelCase      :  Optional[int]												=       AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Union[str, Any]												=       model.to(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Optional[Any]												=       AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE)

				# if batch_size > 1 (which generally leads to padding being required), and
				# if there is not an already assigned pad_token, assign an existing
				# special token to also be the padding token
				if tokenizer.pad_token is None and batch_size > 1:
							__lowerCAmelCase      :  List[Any]												=       list(tokenizer.special_tokens_map_extended.values())
							# check that the model already has at least one special token defined
							assert (
							    len(_SCREAMING_SNAKE_CASE) > 0
							), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
							# assign one of the special tokens to also be the pad token
							tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]})

				if add_start_token:
							# leave room for <BOS> token to be added:
							assert (
							    tokenizer.bos_token is not None
							), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
							__lowerCAmelCase      :  Optional[Any]												=       model.config.max_length - 1
				else:
							__lowerCAmelCase      :  List[str]												=       model.config.max_length

				__lowerCAmelCase      :  List[str]												=       tokenizer(
				    _SCREAMING_SNAKE_CASE       ,			add_special_tokens=_SCREAMING_SNAKE_CASE       ,			padding=_SCREAMING_SNAKE_CASE       ,			truncation=_SCREAMING_SNAKE_CASE       ,			max_length=_SCREAMING_SNAKE_CASE       ,			return_tensors="pt"       ,			return_attention_mask=_SCREAMING_SNAKE_CASE       ,			).to(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  str												=       encodings["input_ids"]
				__lowerCAmelCase      :  Union[str, Any]												=       encodings["attention_mask"]

				# check that each input is long enough:
				if add_start_token:
							assert torch.all(torch.ge(attn_masks.sum(1)       ,			1)), "Each input text must be at least one token long."
				else:
							assert torch.all(
							    torch.ge(attn_masks.sum(1)       ,			2)), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

				__lowerCAmelCase      :  str												=       []
				__lowerCAmelCase      :  List[str]												=       CrossEntropyLoss(reduction="none")

				for start_index in logging.tqdm(range(0       ,			len(_SCREAMING_SNAKE_CASE)       ,			_SCREAMING_SNAKE_CASE)):
							__lowerCAmelCase      :  Union[str, Any]												=       min(start_index + batch_size       ,			len(_SCREAMING_SNAKE_CASE))
							__lowerCAmelCase      :  Optional[Any]												=       encoded_texts[start_index:end_index]
							__lowerCAmelCase      :  Dict												=       attn_masks[start_index:end_index]

							if add_start_token:
										__lowerCAmelCase      :  Tuple												=       torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0)).to(_SCREAMING_SNAKE_CASE)
										__lowerCAmelCase      :  Dict												=       torch.cat([bos_tokens_tensor, encoded_batch]       ,			dim=1)
										__lowerCAmelCase      :  Tuple												=       torch.cat(
										    [torch.ones(bos_tokens_tensor.size()       ,			dtype=torch.intaa).to(_SCREAMING_SNAKE_CASE), attn_mask]       ,			dim=1)

							__lowerCAmelCase      :  List[Any]												=       encoded_batch

							with torch.no_grad():
										__lowerCAmelCase      :  Any												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE).logits

							__lowerCAmelCase      :  List[str]												=       out_logits[..., :-1, :].contiguous()
							__lowerCAmelCase      :  int												=       labels[..., 1:].contiguous()
							__lowerCAmelCase      :  str												=       attn_mask[..., 1:].contiguous()

							__lowerCAmelCase      :  Union[str, Any]												=       torch.expa(
							    (loss_fct(shift_logits.transpose(1       ,			2)       ,			_SCREAMING_SNAKE_CASE) * shift_attention_mask_batch).sum(1)
							    / shift_attention_mask_batch.sum(1))

							ppls += perplexity_batch.tolist()

				return {"perplexities": ppls, "mean_perplexity": np.mean(_SCREAMING_SNAKE_CASE)}




"""simple docstring"""






import unittest

from transformers import SqueezeBertConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, 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 (
	    SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
	    SqueezeBertForMaskedLM,
	    SqueezeBertForMultipleChoice,
	    SqueezeBertForQuestionAnswering,
	    SqueezeBertForSequenceClassification,
	    SqueezeBertForTokenClassification,
	    SqueezeBertModel,
	)



class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	def __init__(     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		List[str]=13       ,			_SCREAMING_SNAKE_CASE:		Tuple=7       ,			_SCREAMING_SNAKE_CASE:		int=True       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=True       ,			_SCREAMING_SNAKE_CASE:		str=False       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=True       ,			_SCREAMING_SNAKE_CASE:		int=99       ,			_SCREAMING_SNAKE_CASE:		int=32       ,			_SCREAMING_SNAKE_CASE:		List[str]=5       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=4       ,			_SCREAMING_SNAKE_CASE:		int=64       ,			_SCREAMING_SNAKE_CASE:		List[str]="gelu"       ,			_SCREAMING_SNAKE_CASE:		str=0.1       ,			_SCREAMING_SNAKE_CASE:		Any=0.1       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=512       ,			_SCREAMING_SNAKE_CASE:		Tuple=16       ,			_SCREAMING_SNAKE_CASE:		Any=2       ,			_SCREAMING_SNAKE_CASE:		List[str]=0.02       ,			_SCREAMING_SNAKE_CASE:		Tuple=3       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=4       ,			_SCREAMING_SNAKE_CASE:		int=None       ,			_SCREAMING_SNAKE_CASE:		int=2       ,			_SCREAMING_SNAKE_CASE:		str=2       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=2       ,			_SCREAMING_SNAKE_CASE:		List[Any]=2       ,			_SCREAMING_SNAKE_CASE:		int=4       ,			_SCREAMING_SNAKE_CASE:		List[str]=1       ,			)				->       Optional[Any]:

				"""simple docstring"""

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       List[str]:

				"""simple docstring"""

				__lowerCAmelCase      :  str												=       ids_tensor([self.batch_size, self.seq_length]       ,			self.vocab_size)

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

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

				__lowerCAmelCase      :  Any												=       self.get_config()

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple)				->       int:

				"""simple docstring"""

				return SqueezeBertConfig(
				    embedding_size=self.hidden_size       ,			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       ,			attention_probs_dropout_prob=self.hidden_dropout_prob       ,			attention_dropout=self.attention_probs_dropout_prob       ,			max_position_embeddings=self.max_position_embeddings       ,			initializer_range=self.initializer_range       ,			q_groups=self.q_groups       ,			k_groups=self.k_groups       ,			v_groups=self.v_groups       ,			post_attention_groups=self.post_attention_groups       ,			intermediate_groups=self.intermediate_groups       ,			output_groups=self.output_groups       ,			)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		List[str]       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Tuple)				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       SqueezeBertModel(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  List[Any]												=       model(_SCREAMING_SNAKE_CASE       ,			_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Dict												=       model(_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.last_hidden_state.shape       ,			(self.batch_size, self.seq_length, self.hidden_size))

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

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       SqueezeBertForMaskedLM(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  Dict												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.vocab_size))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any])				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  str												=       SqueezeBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  Union[str, Any]												=       model(
				    _SCREAMING_SNAKE_CASE       ,			attention_mask=_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 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		Tuple)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       self.num_labels
				__lowerCAmelCase      :  Union[str, Any]												=       SqueezeBertForSequenceClassification(_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  int												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_labels))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[int])				->       Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       self.num_labels
				__lowerCAmelCase      :  Optional[int]												=       SqueezeBertForTokenClassification(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()

				__lowerCAmelCase      :  List[str]												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.num_labels))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		int)				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       self.num_choices
				__lowerCAmelCase      :  str												=       SqueezeBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  int												=       input_ids.unsqueeze(1).expand(-1       ,			self.num_choices       ,			-1).contiguous()
				__lowerCAmelCase      :  Union[str, Any]												=       input_mask.unsqueeze(1).expand(-1       ,			self.num_choices       ,			-1).contiguous()
				__lowerCAmelCase      :  str												=       model(
				    _SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE       ,			)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_choices))







	def 							_SCREAMING_SNAKE_CASE   (     self:		str)				->       List[Any]:

				"""simple docstring"""

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






@require_torch
class 			A__   (  __SCREAMING_SNAKE_CASE  ,		__SCREAMING_SNAKE_CASE  ,		unittest.TestCase							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	(
	    (
	        SqueezeBertModel,
	        SqueezeBertForMaskedLM,
	        SqueezeBertForMultipleChoice,
	        SqueezeBertForQuestionAnswering,
	        SqueezeBertForSequenceClassification,
	        SqueezeBertForTokenClassification,
	    )
	    if is_torch_available()
	    else None
	)
	SCREAMING_SNAKE_CASE          =	(
	    {
	        'feature-extraction': SqueezeBertModel,
	        'fill-mask': SqueezeBertForMaskedLM,
	        'question-answering': SqueezeBertForQuestionAnswering,
	        'text-classification': SqueezeBertForSequenceClassification,
	        'token-classification': SqueezeBertForTokenClassification,
	        'zero-shot': SqueezeBertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE          =	False
	SCREAMING_SNAKE_CASE          =	True
	SCREAMING_SNAKE_CASE          =	False

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       SqueezeBertModelTester(self)
				__lowerCAmelCase      :  Optional[int]												=       ConfigTester(self       ,			config_class=_SCREAMING_SNAKE_CASE       ,			dim=37)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       Tuple:

				"""simple docstring"""

				self.config_tester.run_common_tests()

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int])				->       Any:

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_model(*_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any])				->       List[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_masked_lm(*_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_question_answering(*_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		List[Any])				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  Tuple												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_token_classification(*_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE)







	@slow
	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       Dict:

				"""simple docstring"""

				for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowerCAmelCase      :  Optional[Any]												=       SqueezeBertModel.from_pretrained(_SCREAMING_SNAKE_CASE)
							self.assertIsNotNone(_SCREAMING_SNAKE_CASE)






@require_sentencepiece
@require_tokenizers
@require_torch
class 			A__   (  unittest.TestCase							):




	'''simple docstring'''





	@slow
	def 							_SCREAMING_SNAKE_CASE   (     self:		int)				->       List[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[Any]												=       SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli")

				__lowerCAmelCase      :  List[Any]												=       torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]])
				__lowerCAmelCase      :  List[Any]												=       model(_SCREAMING_SNAKE_CASE)[0]
				__lowerCAmelCase      :  Any												=       torch.Size((1, 3))
				self.assertEqual(output.shape       ,			_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Union[str, Any]												=       torch.tensor([[0.6401, -0.0349, -0.6041]])
				self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE       ,			_SCREAMING_SNAKE_CASE       ,			atol=1e-4))