

from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import tensorflow as tf

				from transformers.models.distilbert.modeling_tf_distilbert import (
				    TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFDistilBertForMaskedLM,
				    TFDistilBertForMultipleChoice,
				    TFDistilBertForQuestionAnswering,
				    TFDistilBertForSequenceClassification,
				    TFDistilBertForTokenClassification,
				    TFDistilBertModel,
				)

class 						__UpperCamelCase    :




	def __init__(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			parent
		UpperCAmelCase_       				=			13
		UpperCAmelCase_       				=			7
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			False
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			99
		UpperCAmelCase_       				=			32
		UpperCAmelCase_       				=			2
		UpperCAmelCase_       				=			4
		UpperCAmelCase_       				=			37
		UpperCAmelCase_       				=			"gelu"
		UpperCAmelCase_       				=			0.1
		UpperCAmelCase_       				=			0.1
		UpperCAmelCase_       				=			512
		UpperCAmelCase_       				=			16
		UpperCAmelCase_       				=			2
		UpperCAmelCase_       				=			0.02
		UpperCAmelCase_       				=			3
		UpperCAmelCase_       				=			4
		UpperCAmelCase_       				=			None




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.vocab_size							)

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

		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		if self.use_labels:
			UpperCAmelCase_       				=			ids_tensor([self.batch_size]		,	self.type_sequence_label_size							)
			UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.num_labels							)
			UpperCAmelCase_       				=			ids_tensor([self.batch_size]		,	self.num_choices							)

		UpperCAmelCase_       				=			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		,	)

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




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModel(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}

		UpperCAmelCase_       				=			model(lowerCAmelCase							)

		UpperCAmelCase_       				=			[input_ids, input_mask]

		UpperCAmelCase_       				=			model(lowerCAmelCase							)

		self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, self.seq_length, self.hidden_size)							)




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertForMaskedLM(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.seq_length, self.vocab_size)							)




	def       __A					(		self	:						Union[str, Any]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertForQuestionAnswering(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{
		    "input_ids": input_ids,
		    "attention_mask": input_mask,
		}
		UpperCAmelCase_       				=			model(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       __A					(		self	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_labels
		UpperCAmelCase_       				=			TFDistilBertForSequenceClassification(lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.num_labels)							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_choices
		UpperCAmelCase_       				=			TFDistilBertForMultipleChoice(lowerCAmelCase							)
		UpperCAmelCase_       				=			tf.tile(tf.expand_dims(lowerCAmelCase		,	1							)		,	(1, self.num_choices, 1)							)
		UpperCAmelCase_       				=			tf.tile(tf.expand_dims(lowerCAmelCase		,	1							)		,	(1, self.num_choices, 1)							)
		UpperCAmelCase_       				=			{
		    "input_ids": multiple_choice_inputs_ids,
		    "attention_mask": multiple_choice_input_mask,
		}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.num_choices)							)




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_labels
		UpperCAmelCase_       				=			TFDistilBertForTokenClassification(lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.seq_length, self.num_labels)							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.prepare_config_and_inputs()
		((UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_))       				=			config_and_inputs
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		return config, inputs_dict


@require_tf
class 						__UpperCamelCase    (					lowercase     ,     lowercase     ,     unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     (
	    (
	        TFDistilBertModel,
	        TFDistilBertForMaskedLM,
	        TFDistilBertForQuestionAnswering,
	        TFDistilBertForSequenceClassification,
	        TFDistilBertForTokenClassification,
	        TFDistilBertForMultipleChoice,
	    )
	    if is_tf_available()
	    else None
	)
	SCREAMING_SNAKE_CASE__    				=     (
	    {
	        'feature-extraction': TFDistilBertModel,
	        'fill-mask': TFDistilBertForMaskedLM,
	        'question-answering': TFDistilBertForQuestionAnswering,
	        'text-classification': TFDistilBertForSequenceClassification,
	        'token-classification': TFDistilBertForTokenClassification,
	        'zero-shot': TFDistilBertForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE__    				=     False
	SCREAMING_SNAKE_CASE__    				=     False




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModelTester(self							)
		UpperCAmelCase_       				=			ConfigTester(self		,	config_class=lowerCAmelCase		,	dim=37							)




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		self.config_tester.run_common_tests()




	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase							)




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase							)




	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase							)




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase							)




	@slow
	def       __A					(		self	:						str							):


		'''simple docstring'''







		for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]							):
			UpperCAmelCase_       				=			TFDistilBertModel.from_pretrained(lowerCAmelCase							)
			self.assertIsNotNone(lowerCAmelCase							)


@require_tf
class 						__UpperCamelCase    (					unittest.TestCase						):




	@slow
	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModel.from_pretrained("distilbert-base-uncased"							)
		UpperCAmelCase_       				=			tf.constant([[0, 1, 2, 3, 4, 5]]							)
		UpperCAmelCase_       				=			model(lowerCAmelCase							)[0]

		UpperCAmelCase_       				=			[1, 6, 768]
		self.assertEqual(output.shape		,	lowerCAmelCase							)

		UpperCAmelCase_       				=			tf.constant(
		    [
		        [
		            [0.19_261_885, -0.13_732_955, 0.4_119_799],
		            [0.22_150_156, -0.07_422_661, 0.39_037_204],
		            [0.22_756_018, -0.0_896_414, 0.3_701_467],
		        ]
		    ]							)
		tf.debugging.assert_near(output[:, :3, :3]		,	lowerCAmelCase		,	atol=1e-4							)







def       __lowerCAmelCase      (						A    ):
	UpperCAmelCase_       				=			generate_pascal_triangle(A    )
	for row_idx in range(A    ):
		# Print left spaces
		for _ in range(num_rows - row_idx - 1    ):
			print(end=" "    )
		# Print row values
		for col_idx in range(row_idx + 1    ):
			if col_idx != row_idx:
				print(triangle[row_idx][col_idx]       ,     end=" "    )
			else:
				print(triangle[row_idx][col_idx]       ,     end=""    )
		print()



def       __lowerCAmelCase      (						A    ):

	if not isinstance(A       ,     A    ):
		raise TypeError("The input value of 'num_rows' should be 'int'"    )

	if num_rows == 0:
		return []
	elif num_rows < 0:
		raise ValueError(
		    "The input value of 'num_rows' should be greater than or equal to 0"    )

	UpperCAmelCase_       				=			[]
	for current_row_idx in range(A    ):
		UpperCAmelCase_       				=			populate_current_row(A       ,     A    )
		triangle.append(A    )
	return triangle



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			[-1] * (current_row_idx + 1)
	# first and last elements of current row are equal to 1
	UpperCAmelCase_				,   UpperCAmelCase_       				=			1, 1
	for current_col_idx in range(1       ,     A    ):
		calculate_current_element(
		    A       ,     A       ,     A       ,     A    )
	return current_row



def       __lowerCAmelCase      (						A       ,     A       ,     A       ,     A       ,     ):
	UpperCAmelCase_       				=			triangle[current_row_idx - 1][current_col_idx - 1]
	UpperCAmelCase_       				=			triangle[current_row_idx - 1][current_col_idx]
	UpperCAmelCase_       				=			above_to_left_elt + above_to_right_elt



def       __lowerCAmelCase      (						A    ):

	if not isinstance(A       ,     A    ):
		raise TypeError("The input value of 'num_rows' should be 'int'"    )

	if num_rows == 0:
		return []
	elif num_rows < 0:
		raise ValueError(
		    "The input value of 'num_rows' should be greater than or equal to 0"    )

	UpperCAmelCase_       				=			[[1]]

	for row_index in range(1       ,     A    ):
		UpperCAmelCase_       				=			[0] + result[-1] + [0]
		UpperCAmelCase_       				=			row_index + 1
		# Calculate the number of distinct elements in a row
		UpperCAmelCase_       				=			sum(divmod(A       ,     2    )    )
		UpperCAmelCase_       				=			[
		    temp_row[i - 1] + temp_row[i] for i in range(1       ,     distinct_elements + 1    )
		]
		UpperCAmelCase_       				=			row_first_half[: (row_index + 1) // 2]
		row_second_half.reverse()
		UpperCAmelCase_       				=			row_first_half + row_second_half
		result.append(A    )

	return result



def       __lowerCAmelCase      (						):
	from collections.abc import Callable
	from timeit import timeit

	def benchmark_a_function(A       ,     A    ) -> None:
		UpperCAmelCase_       				=			F"{func.__name__}({value})"
		UpperCAmelCase_       				=			timeit(F"__main__.{call}"       ,     setup="import __main__"    )
		# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
		print(F"{call:38} -- {timing:.4f} seconds"    )

	for value in range(15    ):  # (1, 7, 14):
		for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
			benchmark_a_function(A       ,     A    )
		print()


if __name__ == "__main__":
				import doctest

				doctest.testmod()
				benchmark()