

'''simple docstring'''



import json
import os
import unittest

from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin



@require_tokenizers
class lowerCamelCase			(  lowercase_	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	GPTaTokenizer
			__snake_case        =	GPTaTokenizerFast
			__snake_case        =	True
			__snake_case        =	{'add_prefix_space': True}
			__snake_case        =	False


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





									'''simple docstring'''
									super().setUp()

									# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
									A__					:       List[Any]     =[
									    """l""",
									    """o""",
									    """w""",
									    """e""",
									    """r""",
									    """s""",
									    """t""",
									    """i""",
									    """d""",
									    """n""",
									    """\u0120""",
									    """\u0120l""",
									    """\u0120n""",
									    """\u0120lo""",
									    """\u0120low""",
									    """er""",
									    """\u0120lowest""",
									    """\u0120newer""",
									    """\u0120wider""",
									    """<unk>""",
									    """<|endoftext|>""",
									]
									A__					:       Tuple     =dict(zip(lowerCAmelCase_		,      range(len(lowerCAmelCase_			)			)			)			)
									A__					:       Dict     =["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
									A__					:       List[str]     ={"""unk_token""": """<unk>"""}

									A__					:       Union[str, Any]     =os.path.join(self.tmpdirname		,      VOCAB_FILES_NAMES["""vocab_file"""]			)
									A__					:       List[str]     =os.path.join(self.tmpdirname		,      VOCAB_FILES_NAMES["""merges_file"""]			)
									with open(self.vocab_file		,      """w"""		,      encoding="""utf-8"""			) as fp:
															fp.write(json.dumps(lowerCAmelCase_			) + """\n"""			)
									with open(self.merges_file		,      """w"""		,      encoding="""utf-8"""			) as fp:
															fp.write("""\n""".join(lowerCAmelCase_			)			)


			def lowercase__						(				self	:						Any		,      **lowerCAmelCase_	:						Any			)      ->		str:





									'''simple docstring'''
									kwargs.update(self.special_tokens_map			)
									return GPTaTokenizer.from_pretrained(self.tmpdirname		,      **lowerCAmelCase_			)


			def lowercase__						(				self	:						Optional[Any]		,      **lowerCAmelCase_	:						str			)      ->		Dict:





									'''simple docstring'''
									kwargs.update(self.special_tokens_map			)
									return GPTaTokenizerFast.from_pretrained(self.tmpdirname		,      **lowerCAmelCase_			)


			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Tuple			)      ->		Any:





									'''simple docstring'''
									A__					:       Any     ="""lower newer"""
									A__					:       int     ="""lower newer"""
									return input_text, output_text


			def lowercase__						(				self	:						Tuple			)      ->		int:





									'''simple docstring'''
									A__					:       List[Any]     =GPTaTokenizer(self.vocab_file		,      self.merges_file		,      **self.special_tokens_map			)
									A__					:       Optional[int]     ="""lower newer"""
									A__					:       str     =["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
									A__					:       List[Any]     =tokenizer.tokenize(lowerCAmelCase_		,      add_prefix_space=lowerCAmelCase_			)
									self.assertListEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

									A__					:       Optional[int]     =tokens + [tokenizer.unk_token]
									A__					:       List[Any]     =[14, 15, 10, 9, 3, 2, 15, 19]
									self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_			)		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						List[str]			)      ->		Tuple:





									'''simple docstring'''
									if not self.test_rust_tokenizer:
															return

									A__					:       int     =self.get_tokenizer()
									A__					:       Optional[int]     =self.get_rust_tokenizer(add_prefix_space=lowerCAmelCase_			)

									A__					:       int     ="""lower newer"""

									# Testing tokenization
									A__					:       str     =tokenizer.tokenize(lowerCAmelCase_		,      add_prefix_space=lowerCAmelCase_			)
									A__					:       int     =rust_tokenizer.tokenize(lowerCAmelCase_			)
									self.assertListEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

									# Testing conversion to ids without special tokens
									A__					:       Tuple     =tokenizer.encode(lowerCAmelCase_		,      add_special_tokens=lowerCAmelCase_		,      add_prefix_space=lowerCAmelCase_			)
									A__					:       Union[str, Any]     =rust_tokenizer.encode(lowerCAmelCase_		,      add_special_tokens=lowerCAmelCase_			)
									self.assertListEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

									# Testing conversion to ids with special tokens
									A__					:       Any     =self.get_rust_tokenizer(add_prefix_space=lowerCAmelCase_			)
									A__					:       Any     =tokenizer.encode(lowerCAmelCase_		,      add_prefix_space=lowerCAmelCase_			)
									A__					:       Optional[Any]     =rust_tokenizer.encode(lowerCAmelCase_			)
									self.assertListEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

									# Testing the unknown token
									A__					:       Optional[Any]     =tokens + [rust_tokenizer.unk_token]
									A__					:       Union[str, Any]     =[14, 15, 10, 9, 3, 2, 15, 19]
									self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowerCAmelCase_			)		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						List[Any]		,      *lowerCAmelCase_	:						int		,      **lowerCAmelCase_	:						str			)      ->		List[str]:





									'''simple docstring'''
									# It's very difficult to mix/test pretokenization with byte-level
									# And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
									pass


			def lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						int=15			)      ->		List[str]:





									'''simple docstring'''
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"			):
																					A__					:       Union[str, Any]     =self.rust_tokenizer_class.from_pretrained(lowerCAmelCase_		,      **lowerCAmelCase_			)

																					# Simple input
																					A__					:       Optional[Any]     ="""This is a simple input"""
																					A__					:       Any     =["""This is a simple input 1""", """This is a simple input 2"""]
																					A__					:       List[str]     =("""This is a simple input""", """This is a pair""")
																					A__					:       Any     =[
																					    ("""This is a simple input 1""", """This is a simple input 2"""),
																					    ("""This is a simple pair 1""", """This is a simple pair 2"""),
																					]

																					# Simple input tests
																					self.assertRaises(lowerCAmelCase_		,      tokenizer_r.encode		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""			)

																					# Simple input
																					self.assertRaises(lowerCAmelCase_		,      tokenizer_r.encode_plus		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""			)

																					# Simple input
																					self.assertRaises(
																					    lowerCAmelCase_		,      tokenizer_r.batch_encode_plus		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""		,      )

																					# Pair input
																					self.assertRaises(lowerCAmelCase_		,      tokenizer_r.encode		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""			)

																					# Pair input
																					self.assertRaises(lowerCAmelCase_		,      tokenizer_r.encode_plus		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""			)

																					# Pair input
																					self.assertRaises(
																					    lowerCAmelCase_		,      tokenizer_r.batch_encode_plus		,      lowerCAmelCase_		,      max_length=lowerCAmelCase_		,      padding="""max_length"""		,      )


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





									'''simple docstring'''
									A__					:       List[str]     =GPTaTokenizer.from_pretrained(self.tmpdirname		,      pad_token="""<pad>"""			)

									# Simple input
									A__					:       Any     ="""This is a simple input"""
									A__					:       Optional[Any]     =["""This is a simple input looooooooong""", """This is a simple input"""]
									A__					:       Tuple     =("""This is a simple input""", """This is a pair""")
									A__					:       int     =[
									    ("""This is a simple input loooooong""", """This is a simple input"""),
									    ("""This is a simple pair loooooong""", """This is a simple pair"""),
									]

									A__					:       Tuple     =tokenizer.pad_token_id

									A__					:       Any     =tokenizer(lowerCAmelCase_		,      padding="""max_length"""		,      max_length=30		,      return_tensors="""np"""			)
									A__					:       Tuple     =tokenizer(lowerCAmelCase_		,      padding=lowerCAmelCase_		,      truncate=lowerCAmelCase_		,      return_tensors="""np"""			)
									A__					:       str     =tokenizer(*lowerCAmelCase_		,      padding="""max_length"""		,      max_length=60		,      return_tensors="""np"""			)
									A__					:       List[str]     =tokenizer(lowerCAmelCase_		,      padding=lowerCAmelCase_		,      truncate=lowerCAmelCase_		,      return_tensors="""np"""			)

									# s
									# test single string max_length padding
									self.assertEqual(out_s["""input_ids"""].shape[-1]		,      30			)
									self.assertTrue(pad_token_id in out_s["""input_ids"""]			)
									self.assertTrue(0 in out_s["""attention_mask"""]			)

									# s2
									# test automatic padding
									self.assertEqual(out_sa["""input_ids"""].shape[-1]		,      33			)
									# long slice doesn't have padding
									self.assertFalse(pad_token_id in out_sa["""input_ids"""][0]			)
									self.assertFalse(0 in out_sa["""attention_mask"""][0]			)
									# short slice does have padding
									self.assertTrue(pad_token_id in out_sa["""input_ids"""][1]			)
									self.assertTrue(0 in out_sa["""attention_mask"""][1]			)

									# p
									# test single pair max_length padding
									self.assertEqual(out_p["""input_ids"""].shape[-1]		,      60			)
									self.assertTrue(pad_token_id in out_p["""input_ids"""]			)
									self.assertTrue(0 in out_p["""attention_mask"""]			)

									# p2
									# test automatic padding pair
									self.assertEqual(out_pa["""input_ids"""].shape[-1]		,      52			)
									# long slice pair doesn't have padding
									self.assertFalse(pad_token_id in out_pa["""input_ids"""][0]			)
									self.assertFalse(0 in out_pa["""attention_mask"""][0]			)
									# short slice pair does have padding
									self.assertTrue(pad_token_id in out_pa["""input_ids"""][1]			)
									self.assertTrue(0 in out_pa["""attention_mask"""][1]			)


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





									'''simple docstring'''
									A__					:       int     ="""$$$"""
									A__					:       Union[str, Any]     =GPTaTokenizer.from_pretrained(self.tmpdirname		,      bos_token=lowerCAmelCase_		,      add_bos_token=lowerCAmelCase_			)

									A__					:       Optional[Any]     ="""This is a simple input"""
									A__					:       Tuple     =["""This is a simple input 1""", """This is a simple input 2"""]

									A__					:       Tuple     =tokenizer.bos_token_id

									A__					:       Tuple     =tokenizer(lowerCAmelCase_			)
									A__					:       str     =tokenizer(lowerCAmelCase_			)

									self.assertEqual(out_s.input_ids[0]		,      lowerCAmelCase_			)
									self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids			)			)

									A__					:       Tuple     =tokenizer.decode(out_s.input_ids			)
									A__					:       List[Any]     =tokenizer.batch_decode(out_sa.input_ids			)

									self.assertEqual(decode_s.split()[0]		,      lowerCAmelCase_			)
									self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa			)			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		str:





									'''simple docstring'''
									pass



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





									'''simple docstring'''
									# TODO: change to self.get_tokenizers() when the fast version is implemented
									A__					:       Any     =[self.get_tokenizer(do_lower_case=lowerCAmelCase_		,      add_bos_token=lowerCAmelCase_			)]
									for tokenizer in tokenizers:
															with self.subTest(f"{tokenizer.__class__.__name__}"			):
																					A__					:       str     ="""Encode this."""
																					A__					:       Any     ="""This one too please."""
																					A__					:       Union[str, Any]     =tokenizer.encode(lowerCAmelCase_		,      add_special_tokens=lowerCAmelCase_			)
																					encoded_sequence += tokenizer.encode(lowerCAmelCase_		,      add_special_tokens=lowerCAmelCase_			)
																					A__					:       int     =tokenizer.encode_plus(
																					    lowerCAmelCase_		,      lowerCAmelCase_		,      add_special_tokens=lowerCAmelCase_		,      return_special_tokens_mask=lowerCAmelCase_		,      )
																					A__					:       Dict     =encoded_sequence_dict["""input_ids"""]
																					A__					:       List[Any]     =encoded_sequence_dict["""special_tokens_mask"""]
																					self.assertEqual(len(lowerCAmelCase_			)		,      len(lowerCAmelCase_			)			)

																					A__					:       int     =[
																					    (x if not special_tokens_mask[i] else None) for i, x in enumerate(lowerCAmelCase_			)
																					]
																					A__					:       List[str]     =[x for x in filtered_sequence if x is not None]
																					self.assertEqual(lowerCAmelCase_		,      lowerCAmelCase_			)



@require_tokenizers
class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






			def lowercase__						(				self	:						int			)      ->		int:





									'''simple docstring'''
									# More context:
									# https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
									# https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
									# https://github.com/huggingface/transformers/pull/17088#discussion_r871246439

									A__					:       Optional[Any]     =AutoTokenizer.from_pretrained("""facebook/opt-350m"""		,      from_slow=lowerCAmelCase_			)
									A__					:       Tuple     ="""A photo of a cat"""

									A__					:       int     =tokenizer.encode(
									    lowerCAmelCase_		,      )
									self.assertEqual(lowerCAmelCase_		,      [2, 2_50, 13_45, 9, 10, 47_58]			)
									tokenizer.save_pretrained("""test_opt"""			)

									A__					:       List[str]     =AutoTokenizer.from_pretrained("""./test_opt"""			)
									A__					:       Union[str, Any]     =tokenizer.encode(
									    lowerCAmelCase_		,      )
									self.assertEqual(lowerCAmelCase_		,      [2, 2_50, 13_45, 9, 10, 47_58]			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Tuple     =AutoTokenizer.from_pretrained("""facebook/opt-350m"""		,      use_slow=lowerCAmelCase_			)
									A__					:       str     ="""A photo of a cat"""

									A__					:       Tuple     =tokenizer.encode(
									    lowerCAmelCase_		,      )
									# Same as above
									self.assertEqual(lowerCAmelCase_		,      [2, 2_50, 13_45, 9, 10, 47_58]			)



			@unittest.skip("""This test is failing because of a bug in the fast tokenizer"""			)
			def lowercase__						(				self	:						List[Any]			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       Any     =AutoTokenizer.from_pretrained("""facebook/opt-350m"""		,      from_slow=lowerCAmelCase_			)

									A__					:       Optional[Any]     ="""bos"""
									A__					:       Any     =tokenizer.get_vocab()["""bos"""]

									A__					:       List[str]     ="""A photo of a cat"""
									A__					:       List[str]     =tokenizer.encode(
									    lowerCAmelCase_		,      )
									# We changed the bos token
									self.assertEqual(lowerCAmelCase_		,      [3_19_57, 2_50, 13_45, 9, 10, 47_58]			)
									tokenizer.save_pretrained("""./tok"""			)
									A__					:       List[Any]     =AutoTokenizer.from_pretrained("""./tok"""			)
									self.assertTrue(tokenizer.is_fast			)
									A__					:       Tuple     =tokenizer.encode(
									    lowerCAmelCase_		,      )
									self.assertEqual(lowerCAmelCase_		,      [3_19_57, 2_50, 13_45, 9, 10, 47_58]			)




'''simple docstring'''



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			(  lowercase_						):



			'''simple docstring'''






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





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


			def lowercase__						(				self	:						int			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Dict     =ids_tensor([self.batch_size, self.seq_length]		,      self.vocab_size			)

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

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

									A__					:       str     =self.get_config()

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


			def lowercase__						(				self	:						Tuple			)      ->		List[Any]:





									'''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 lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						List[Any]			)      ->		str:





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertModel(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Dict     =model(lowerCAmelCase_		,      lowerCAmelCase_			)
									A__					:       List[str]     =model(lowerCAmelCase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)


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





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertForMaskedLM(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size)			)


			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Dict     =DistilBertForQuestionAnswering(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      start_positions=lowerCAmelCase_		,      end_positions=lowerCAmelCase_			)
									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 lowercase__						(				self	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Dict			)      ->		Tuple:





									'''simple docstring'''
									A__					:       List[Any]     =self.num_labels
									A__					:       Dict     =DistilBertForSequenceClassification(lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)			)


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





									'''simple docstring'''
									A__					:       Optional[int]     =self.num_labels
									A__					:       Union[str, Any]     =DistilBertForTokenClassification(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()

									A__					:       List[Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.num_labels)			)


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





									'''simple docstring'''
									A__					:       int     =self.num_choices
									A__					:       Tuple     =DistilBertForMultipleChoice(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       int     =input_ids.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       int     =input_mask.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_		,      )
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_choices)			)



			def lowercase__						(				self	:						Tuple			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =self.prepare_config_and_inputs()
									((A__)   ,						(A__)   ,						(A__)   ,						(A__)   ,						(A__)   ,						(A__))					:       List[str]     =config_and_inputs
									A__					:       str     ={"""input_ids""": input_ids, """attention_mask""": input_mask}
									return config, inputs_dict



@require_torch
class lowerCamelCase			(  lowercase_	,						lowercase_	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			__snake_case        =	(
			    {
			        'feature-extraction': DistilBertModel,
			        'fill-mask': DistilBertForMaskedLM,
			        'question-answering': DistilBertForQuestionAnswering,
			        'text-classification': DistilBertForSequenceClassification,
			        'token-classification': DistilBertForTokenClassification,
			        'zero-shot': DistilBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True


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





									'''simple docstring'''
									A__					:       Any     =DistilBertModelTester(self			)
									A__					:       Tuple     =ConfigTester(self		,      config_class=lowerCAmelCase_		,      dim=37			)


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





									'''simple docstring'''
									self.config_tester.run_common_tests()


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





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase_			)


			def lowercase__						(				self	:						Any			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Tuple     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       str     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       Any     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase_			)


			def lowercase__						(				self	:						List[str]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       List[Any]     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase_			)


			@slow
			def lowercase__						(				self	:						Union[str, Any]			)      ->		Dict:





									'''simple docstring'''
									for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       Optional[int]     =DistilBertModel.from_pretrained(lowerCAmelCase_			)
															self.assertIsNotNone(lowerCAmelCase_			)



			@slow
			@require_torch_gpu
			def lowercase__						(				self	:						Tuple			)      ->		Any:





									'''simple docstring'''
									A__   ,						A__					:       List[str]     =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

															A__					:       Any     =True
															A__					:       Optional[Any]     =model_class(config=lowerCAmelCase_			)

															A__					:       Dict     =self._prepare_for_class(lowerCAmelCase_		,      lowerCAmelCase_			)
															A__					:       Optional[int]     =torch.jit.trace(
															    lowerCAmelCase_		,      (inputs_dict["""input_ids"""].to("""cpu"""			), inputs_dict["""attention_mask"""].to("""cpu"""			))			)

															with tempfile.TemporaryDirectory() as tmp:
																					torch.jit.save(lowerCAmelCase_		,      os.path.join(lowerCAmelCase_		,      """traced_model.pt"""			)			)
																					A__					:       List[Any]     =torch.jit.load(os.path.join(lowerCAmelCase_		,      """traced_model.pt"""			)		,      map_location=lowerCAmelCase_			)
																					loaded(inputs_dict["""input_ids"""].to(lowerCAmelCase_			)		,      inputs_dict["""attention_mask"""].to(lowerCAmelCase_			)			)



@require_torch
class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






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





									'''simple docstring'''
									A__					:       List[str]     =DistilBertModel.from_pretrained("""distilbert-base-uncased"""			)
									A__					:       Optional[Any]     =torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]			)
									A__					:       int     =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
									with torch.no_grad():
															A__					:       Any     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_			)[0]
									A__					:       Tuple     =torch.Size((1, 11, 7_68)			)
									self.assertEqual(output.shape		,      lowerCAmelCase_			)
									A__					:       Optional[int]     =torch.tensor(
									    [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]			)

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

