


'''simple docstring'''
import os
import tempfile
import unittest

from transformers import FlaubertConfig, 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 (
		    FlaubertForMultipleChoice,
		    FlaubertForQuestionAnswering,
		    FlaubertForQuestionAnsweringSimple,
		    FlaubertForSequenceClassification,
		    FlaubertForTokenClassification,
		    FlaubertModel,
		    FlaubertWithLMHeadModel,
		)
		from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class      lowercase			(							A__      ):

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_					,     UpperCamelCase_=13					,     UpperCamelCase_=7					,     UpperCamelCase_=True					,     UpperCamelCase_=True					,     UpperCamelCase_=True					,     UpperCamelCase_=True					,     UpperCamelCase_=True					,     UpperCamelCase_=False					,     UpperCamelCase_=False					,     UpperCamelCase_=False					,     UpperCamelCase_=2					,     UpperCamelCase_=99					,     UpperCamelCase_=0					,     UpperCamelCase_=32					,     UpperCamelCase_=5					,     UpperCamelCase_=4					,     UpperCamelCase_=0.1					,     UpperCamelCase_=0.1					,     UpperCamelCase_=512					,     UpperCamelCase_=12					,     UpperCamelCase_=2					,     UpperCamelCase_=0.02					,     UpperCamelCase_=3					,     UpperCamelCase_=4					,     UpperCamelCase_="last"					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     ):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				parent
							UpperCamelCase__     :str							      =				batch_size
							UpperCamelCase__     :Optional[int]							      =				seq_length
							UpperCamelCase__     :str							      =				is_training
							UpperCamelCase__     :Dict							      =				use_input_lengths
							UpperCamelCase__     :Dict							      =				use_token_type_ids
							UpperCamelCase__     :Optional[int]							      =				use_labels
							UpperCamelCase__     :Optional[Any]							      =				gelu_activation
							UpperCamelCase__     :Optional[int]							      =				sinusoidal_embeddings
							UpperCamelCase__     :str							      =				causal
							UpperCamelCase__     :Optional[Any]							      =				asm
							UpperCamelCase__     :Union[str, Any]							      =				n_langs
							UpperCamelCase__     :Dict							      =				vocab_size
							UpperCamelCase__     :List[str]							      =				n_special
							UpperCamelCase__     :str							      =				hidden_size
							UpperCamelCase__     :List[str]							      =				num_hidden_layers
							UpperCamelCase__     :Optional[Any]							      =				num_attention_heads
							UpperCamelCase__     :Union[str, Any]							      =				hidden_dropout_prob
							UpperCamelCase__     :Optional[int]							      =				attention_probs_dropout_prob
							UpperCamelCase__     :List[Any]							      =				max_position_embeddings
							UpperCamelCase__     :Optional[Any]							      =				type_vocab_size
							UpperCamelCase__     :Tuple							      =				type_sequence_label_size
							UpperCamelCase__     :str							      =				initializer_range
							UpperCamelCase__     :str							      =				num_labels
							UpperCamelCase__     :int							      =				num_choices
							UpperCamelCase__     :Any							      =				summary_type
							UpperCamelCase__     :Union[str, Any]							      =				use_proj
							UpperCamelCase__     :List[Any]							      =				scope




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Optional[Any]							      =				ids_tensor([self.batch_size, self.seq_length]					,     self.vocab_size							)
							UpperCamelCase__     :List[str]							      =				random_attention_mask([self.batch_size, self.seq_length]							)

							UpperCamelCase__     :Union[str, Any]							      =				None
							if self.use_input_lengths:
												UpperCamelCase__     :Optional[Any]							      =				(
												    ids_tensor([self.batch_size]					,     vocab_size=2							) + self.seq_length - 2
												)  # small variation of seq_length

							UpperCamelCase__     :Union[str, Any]							      =				None
							if self.use_token_type_ids:
												UpperCamelCase__     :Tuple							      =				ids_tensor([self.batch_size, self.seq_length]					,     self.n_langs							)

							UpperCamelCase__     :str							      =				None
							UpperCamelCase__     :Union[str, Any]							      =				None
							UpperCamelCase__     :Tuple							      =				None
							if self.use_labels:
												UpperCamelCase__     :Optional[int]							      =				ids_tensor([self.batch_size]					,     self.type_sequence_label_size							)
												UpperCamelCase__     :Optional[int]							      =				ids_tensor([self.batch_size, self.seq_length]					,     self.num_labels							)
												UpperCamelCase__     :str							      =				ids_tensor([self.batch_size]					,     2							).float()
												UpperCamelCase__     :str							      =				ids_tensor([self.batch_size]					,     self.num_choices							)

							UpperCamelCase__     :Union[str, Any]							      =				self.get_config()

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_lengths,
							    sequence_labels,
							    token_labels,
							    is_impossible_labels,
							    choice_labels,
							    input_mask,
							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							return FlaubertConfig(
							    vocab_size=self.vocab_size					,     n_special=self.n_special					,     emb_dim=self.hidden_size					,     n_layers=self.num_hidden_layers					,     n_heads=self.num_attention_heads					,     dropout=self.hidden_dropout_prob					,     attention_dropout=self.attention_probs_dropout_prob					,     gelu_activation=self.gelu_activation					,     sinusoidal_embeddings=self.sinusoidal_embeddings					,     asm=self.asm					,     causal=self.causal					,     n_langs=self.n_langs					,     max_position_embeddings=self.max_position_embeddings					,     initializer_range=self.initializer_range					,     summary_type=self.summary_type					,     use_proj=self.use_proj					,     )




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Tuple							      =				FlaubertModel(config=UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()
							UpperCamelCase__     :Any							      =				model(UpperCamelCase_					,     lengths=UpperCamelCase_					,     langs=UpperCamelCase_							)
							UpperCamelCase__     :str							      =				model(UpperCamelCase_					,     langs=UpperCamelCase_							)
							UpperCamelCase__     :int							      =				model(UpperCamelCase_							)
							self.parent.assertEqual(result.last_hidden_state.shape					,     (self.batch_size, self.seq_length, self.hidden_size)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Optional[Any]							      =				FlaubertWithLMHeadModel(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

							UpperCamelCase__     :List[Any]							      =				model(UpperCamelCase_					,     token_type_ids=UpperCamelCase_					,     labels=UpperCamelCase_							)
							self.parent.assertEqual(result.loss.shape					,     ()							)
							self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				FlaubertForQuestionAnsweringSimple(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

							UpperCamelCase__     :Optional[int]							      =				model(UpperCamelCase_							)

							UpperCamelCase__     :Tuple							      =				model(UpperCamelCase_					,     start_positions=UpperCamelCase_					,     end_positions=UpperCamelCase_							)
							self.parent.assertEqual(result.start_logits.shape					,     (self.batch_size, self.seq_length)							)
							self.parent.assertEqual(result.end_logits.shape					,     (self.batch_size, self.seq_length)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :List[Any]							      =				FlaubertForQuestionAnswering(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

							UpperCamelCase__     :int							      =				model(UpperCamelCase_							)

							UpperCamelCase__     :Any							      =				model(
							    UpperCamelCase_					,     start_positions=UpperCamelCase_					,     end_positions=UpperCamelCase_					,     cls_index=UpperCamelCase_					,     is_impossible=UpperCamelCase_					,     p_mask=UpperCamelCase_					,     )

							UpperCamelCase__     :Any							      =				model(
							    UpperCamelCase_					,     start_positions=UpperCamelCase_					,     end_positions=UpperCamelCase_					,     cls_index=UpperCamelCase_					,     is_impossible=UpperCamelCase_					,     )

							((UpperCamelCase__)      ,       )     :List[str]							      =				result_with_labels.to_tuple()

							UpperCamelCase__     :List[Any]							      =				model(UpperCamelCase_					,     start_positions=UpperCamelCase_					,     end_positions=UpperCamelCase_							)

							((UpperCamelCase__)      ,       )     :List[str]							      =				result_with_labels.to_tuple()

							self.parent.assertEqual(result_with_labels.loss.shape					,     ()							)
							self.parent.assertEqual(result.start_top_log_probs.shape					,     (self.batch_size, model.config.start_n_top)							)
							self.parent.assertEqual(result.start_top_index.shape					,     (self.batch_size, model.config.start_n_top)							)
							self.parent.assertEqual(
							    result.end_top_log_probs.shape					,     (self.batch_size, model.config.start_n_top * model.config.end_n_top)							)
							self.parent.assertEqual(
							    result.end_top_index.shape					,     (self.batch_size, model.config.start_n_top * model.config.end_n_top)							)
							self.parent.assertEqual(result.cls_logits.shape					,     (self.batch_size,)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Union[str, Any]							      =				FlaubertForSequenceClassification(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

							UpperCamelCase__     :Union[str, Any]							      =				model(UpperCamelCase_							)
							UpperCamelCase__     :Tuple							      =				model(UpperCamelCase_					,     labels=UpperCamelCase_							)

							self.parent.assertEqual(result.loss.shape					,     ()							)
							self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.type_sequence_label_size)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Any							      =				self.num_labels
							UpperCamelCase__     :int							      =				FlaubertForTokenClassification(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

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




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Optional[int]							      =				self.num_choices
							UpperCamelCase__     :Any							      =				FlaubertForMultipleChoice(config=UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()
							UpperCamelCase__     :List[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__     :Optional[int]							      =				input_mask.unsqueeze(1							).expand(-1					,     self.num_choices					,     -1							).contiguous()
							UpperCamelCase__     :Dict							      =				model(
							    UpperCamelCase_					,     attention_mask=UpperCamelCase_					,     token_type_ids=UpperCamelCase_					,     labels=UpperCamelCase_					,     )
							self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.num_choices)							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				self.prepare_config_and_inputs()
							(
							    (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       (
							    UpperCamelCase__
							)      ,       
							)     :Tuple							      =				config_and_inputs
							UpperCamelCase__     :Tuple							      =				{
							    '''input_ids''': input_ids,
							    '''token_type_ids''': token_type_ids,
							    '''lengths''': input_lengths,
							    '''attention_mask''': input_mask,
							}
							return config, inputs_dict



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

		"""simple docstring"""

		_a									=       (
		    (
		        FlaubertModel,
		        FlaubertWithLMHeadModel,
		        FlaubertForQuestionAnswering,
		        FlaubertForQuestionAnsweringSimple,
		        FlaubertForSequenceClassification,
		        FlaubertForTokenClassification,
		        FlaubertForMultipleChoice,
		    )
		    if is_torch_available()
		    else ()
		)
		_a									=       (
		    {
		        'feature-extraction': FlaubertModel,
		        'fill-mask': FlaubertWithLMHeadModel,
		        'question-answering': FlaubertForQuestionAnsweringSimple,
		        'text-classification': FlaubertForSequenceClassification,
		        'token-classification': FlaubertForTokenClassification,
		        'zero-shot': FlaubertForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							if (
							    pipeline_test_casse_name == "QAPipelineTests"
							    and tokenizer_name is not None
							    and not tokenizer_name.endswith('''Fast'''							)
							):
												# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
												# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
												# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
												return True

							return False




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_=False							):

							'''simple docstring'''


							UpperCamelCase__     :Any							      =				super()._prepare_for_class(UpperCamelCase_					,     UpperCamelCase_					,     return_labels=UpperCamelCase_							)

							if return_labels:
												if model_class.__name__ == "FlaubertForQuestionAnswering":
																	UpperCamelCase__     :Optional[Any]							      =				torch.zeros(
																	    self.model_tester.batch_size					,     dtype=torch.long					,     device=UpperCamelCase_							)
																	UpperCamelCase__     :int							      =				torch.zeros(
																	    self.model_tester.batch_size					,     dtype=torch.long					,     device=UpperCamelCase_							)

							return inputs_dict




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :List[Any]							      =				FlaubertModelTester(self							)
							UpperCamelCase__     :str							      =				ConfigTester(self					,     config_class=UpperCamelCase_					,     emb_dim=37							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							self.config_tester.run_common_tests()




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Tuple							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Optional[int]							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :List[Any]							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :List[str]							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Any							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Optional[Any]							      =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_							)




		@slow
		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCamelCase__     :List[str]							      =				FlaubertModel.from_pretrained(UpperCamelCase_							)
												self.assertIsNotNone(UpperCamelCase_							)




		@slow
		@require_torch_gpu
		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__      ,       UpperCamelCase__     :Dict							      =				self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
												# FlauBertForMultipleChoice behaves incorrectly in JIT environments.
												if model_class == FlaubertForMultipleChoice:
																	return

												UpperCamelCase__     :int							      =				True
												UpperCamelCase__     :Optional[Any]							      =				model_class(config=UpperCamelCase_							)

												UpperCamelCase__     :Union[str, Any]							      =				self._prepare_for_class(UpperCamelCase_					,     UpperCamelCase_							)
												UpperCamelCase__     :int							      =				torch.jit.trace(
												    UpperCamelCase_					,     (inputs_dict['''input_ids'''].to('''cpu'''							), inputs_dict['''attention_mask'''].to('''cpu'''							))							)

												with tempfile.TemporaryDirectory() as tmp:
																	torch.jit.save(UpperCamelCase_					,     os.path.join(UpperCamelCase_					,     '''traced_model.pt'''							)							)
																	UpperCamelCase__     :int							      =				torch.jit.load(os.path.join(UpperCamelCase_					,     '''traced_model.pt'''							)					,     map_location=UpperCamelCase_							)
																	loaded(inputs_dict['''input_ids'''].to(UpperCamelCase_							)					,     inputs_dict['''attention_mask'''].to(UpperCamelCase_							)							)



@require_torch
class      lowercase			(							unittest.TestCase      ):

		"""simple docstring"""

		@slow
		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							UpperCamelCase__     :Union[str, Any]							      =				FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased'''							)
							UpperCamelCase__     :List[str]							      =				torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]							)
							with torch.no_grad():
												UpperCamelCase__     :Optional[Any]							      =				model(UpperCamelCase_							)[0]
							UpperCamelCase__     :Union[str, Any]							      =				torch.Size((1, 11, 768)							)
							self.assertEqual(output.shape					,     UpperCamelCase_							)
							UpperCamelCase__     :List[str]							      =				torch.tensor(
							    [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]]							)

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



'''simple docstring'''
from __future__ import annotations

from decimal import Decimal
from math import *  # noqa: F403

from sympy import diff


def     a   (    __a				,      __a				,      __a = 10**-10     )						->			float:



					'''simple docstring'''






					UpperCamelCase__     :Tuple							      =				a
					while True:
										UpperCamelCase__     :Dict							      =				Decimal(__a     ) - (
										    Decimal(eval(__a     )     ) / Decimal(eval(str(diff(__a     )     )     )     )  # noqa: S307
										)
										# This number dictates the accuracy of the answer
										if abs(eval(__a     )     ) < precision:  # noqa: S307
															return float(__a     )


# Let's Execute
if __name__ == "__main__":
		# Find root of trigonometric function
		# Find value of pi
		print(F"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""")
		# Find root of polynomial
		print(F"""The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}""")
		# Find Square Root of 5
		print(F"""The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}""")
		# Exponential Roots
		print(F"""The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}""")