






"""simple docstring"""







import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
	import torch

	from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin







class        _SCREAMING_SNAKE_CASE						:





							"""simple docstring"""





							def __init__(   self:     List[str]				,		__A:     Optional[int]				,		__A:     Dict=None				,		__A:     str=None				,		__A:     Any=None				,		__A:     Optional[Any]="resnet50"				,		__A:     Any=3				,		__A:     Union[str, Any]=32				,		__A:     Optional[int]=3				,		__A:     Any=True				,		__A:     str=True				,		):

												'''simple docstring'''

												a__          =  parent
												a__          =  out_indices if out_indices is not None else [4]
												a__          =  stage_names
												a__          =  out_features
												a__          =  backbone
												a__          =  batch_size
												a__          =  image_size
												a__          =  num_channels
												a__          =  use_pretrained_backbone
												a__          =  is_training




							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )
												a__          =  self.get_config()

												return config, pixel_values




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												return TimmBackboneConfig(
												    image_size=self.image_size				,		num_channels=self.num_channels				,		out_features=self.out_features				,		out_indices=self.out_indices				,		stage_names=self.stage_names				,		use_pretrained_backbone=self.use_pretrained_backbone				,		backbone=self.backbone				,		)




							def  lowercase		(   self:     Dict				,		__A:     int				,		__A:     Dict    ):

												'''simple docstring'''

												a__          =  TimmBackbone(config=__A    )
												model.to(__A    )
												model.eval()
												with torch.no_grad():
																	a__          =  model(__A    )
												self.parent.assertEqual(
												    result.feature_map[-1].shape				,		(self.batch_size, model.channels[-1], 14, 14)				,		)





							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												a__       ,a__          =  config_and_inputs
												a__          =  {'''pixel_values''': pixel_values}
												return config, inputs_dict







@require_torch
@require_timm
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , __snake_case       , __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =	(TimmBackbone,) if is_torch_available() else ()
							_SCREAMING_SNAKE_CASE    =	{'feature-extraction': TimmBackbone} if is_torch_available() else {}
							_SCREAMING_SNAKE_CASE    =	False
							_SCREAMING_SNAKE_CASE    =	False
							_SCREAMING_SNAKE_CASE    =	False
							_SCREAMING_SNAKE_CASE    =	False




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  TimmBackboneModelTester(self    )
												a__          =  ConfigTester(self				,		config_class=__A				,		has_text_modality=__A    )




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												self.config_tester.create_and_test_config_to_json_string()
												self.config_tester.create_and_test_config_to_json_file()
												self.config_tester.create_and_test_config_from_and_save_pretrained()
												self.config_tester.create_and_test_config_with_num_labels()
												self.config_tester.check_config_can_be_init_without_params()
												self.config_tester.check_config_arguments_init()




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

												'''simple docstring'''

												a__          =  '''resnet18'''
												a__          =  '''microsoft/resnet-18'''

												a__          =  AutoBackbone.from_pretrained(__A				,		use_timm_backbone=__A    )
												a__          =  AutoBackbone.from_pretrained(__A    )

												self.assertEqual(len(timm_model.out_features    )				,		len(transformers_model.out_features    )    )
												self.assertEqual(len(timm_model.stage_names    )				,		len(transformers_model.stage_names    )    )
												self.assertEqual(timm_model.channels				,		transformers_model.channels    )
												# Out indices are set to the last layer by default. For timm models, we don't know
												# the number of layers in advance, so we set it to (-1,), whereas for transformers
												# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
												self.assertEqual(timm_model.out_indices				,		(-1,)    )
												self.assertEqual(transformers_model.out_indices				,		[len(timm_model.stage_names    ) - 1]    )

												a__          =  AutoBackbone.from_pretrained(__A				,		use_timm_backbone=__A				,		out_indices=[1, 2, 3]    )
												a__          =  AutoBackbone.from_pretrained(__A				,		out_indices=[1, 2, 3]    )

												self.assertEqual(timm_model.out_indices				,		transformers_model.out_indices    )
												self.assertEqual(len(timm_model.out_features    )				,		len(transformers_model.out_features    )    )
												self.assertEqual(timm_model.channels				,		transformers_model.channels    )




							@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking'''    )
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute'''    )
							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone initialization is managed on the timm side'''    )
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''    )
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''    )
							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint'''    )
							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''    )
							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.'''    )
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.'''    )
							def  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''    )
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''    )
							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.'''    )
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												pass




							@unittest.skip('''TimmBackbone doesn\'t support output_attentions.'''    )
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												pass




							@unittest.skip('''Safetensors is not supported by timm.'''    )
							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												pass




							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''    )
							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												pass




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

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	a__          =  model_class(__A    )
																	a__          =  inspect.signature(model.forward    )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	a__          =  [*signature.parameters.keys()]

																	a__          =  ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]				,		__A    )




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

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  True
												a__          =  self.has_attentions

												# no need to test all models as different heads yield the same functionality
												a__          =  self.all_model_classes[0]
												a__          =  model_class(__A    )
												model.to(__A    )

												a__          =  self._prepare_for_class(__A				,		__A    )
												a__          =  model(**__A    )
												a__          =  outputs[0][-1]

												# Encoder-/Decoder-only models
												a__          =  outputs.hidden_states[0]
												hidden_states.retain_grad()

												if self.has_attentions:
																	a__          =  outputs.attentions[0]
																	attentions.retain_grad()

												output.flatten()[0].backward(retain_graph=__A    )

												self.assertIsNotNone(hidden_states.grad    )

												if self.has_attentions:
																	self.assertIsNotNone(attentions.grad    )





							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	a__          =  model_class(__A    )
																	model.to(__A    )
																	model.eval()
																	a__          =  model(**__A    )

																	self.assertEqual(len(result.feature_maps    )				,		len(config.out_indices    )    )
																	self.assertEqual(len(model.channels    )				,		len(config.out_indices    )    )

																	# Check output of last stage is taken if out_features=None, out_indices=None
																	a__          =  copy.deepcopy(__A    )
																	a__          =  None
																	a__          =  model_class(__A    )
																	model.to(__A    )
																	model.eval()
																	a__          =  model(**__A    )

																	self.assertEqual(len(result.feature_maps    )				,		1    )
																	self.assertEqual(len(model.channels    )				,		1    )

																	# Check backbone can be initialized with fresh weights
																	a__          =  copy.deepcopy(__A    )
																	a__          =  False
																	a__          =  model_class(__A    )
																	model.to(__A    )
																	model.eval()
																	a__          =  model(**__A    )










"""simple docstring"""







import unittest

import numpy as np

from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
	import jax.numpy as jnp

	from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
	    FlaxRobertaPreLayerNormForCausalLM,
	    FlaxRobertaPreLayerNormForMaskedLM,
	    FlaxRobertaPreLayerNormForMultipleChoice,
	    FlaxRobertaPreLayerNormForQuestionAnswering,
	    FlaxRobertaPreLayerNormForSequenceClassification,
	    FlaxRobertaPreLayerNormForTokenClassification,
	    FlaxRobertaPreLayerNormModel,
	)







class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							def __init__(   self:     List[str]				,		__A:     Optional[Any]				,		__A:     List[Any]=13				,		__A:     Optional[int]=7				,		__A:     Any=True				,		__A:     str=True				,		__A:     Any=True				,		__A:     str=True				,		__A:     Optional[Any]=99				,		__A:     Union[str, Any]=32				,		__A:     str=5				,		__A:     Any=4				,		__A:     List[str]=37				,		__A:     Union[str, Any]="gelu"				,		__A:     str=0.1				,		__A:     Tuple=0.1				,		__A:     Optional[Any]=512				,		__A:     Union[str, Any]=16				,		__A:     str=2				,		__A:     Any=0.0_2				,		__A:     Tuple=4				,		):

												'''simple docstring'''

												a__          =  parent
												a__          =  batch_size
												a__          =  seq_length
												a__          =  is_training
												a__          =  use_attention_mask
												a__          =  use_token_type_ids
												a__          =  use_labels
												a__          =  vocab_size
												a__          =  hidden_size
												a__          =  num_hidden_layers
												a__          =  num_attention_heads
												a__          =  intermediate_size
												a__          =  hidden_act
												a__          =  hidden_dropout_prob
												a__          =  attention_probs_dropout_prob
												a__          =  max_position_embeddings
												a__          =  type_vocab_size
												a__          =  type_sequence_label_size
												a__          =  initializer_range
												a__          =  num_choices




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

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

												a__          =  None
												if self.use_attention_mask:
																	a__          =  random_attention_mask([self.batch_size, self.seq_length]    )

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

												a__          =  RobertaPreLayerNormConfig(
												    vocab_size=self.vocab_size				,		hidden_size=self.hidden_size				,		num_hidden_layers=self.num_hidden_layers				,		num_attention_heads=self.num_attention_heads				,		intermediate_size=self.intermediate_size				,		hidden_act=self.hidden_act				,		hidden_dropout_prob=self.hidden_dropout_prob				,		attention_probs_dropout_prob=self.attention_probs_dropout_prob				,		max_position_embeddings=self.max_position_embeddings				,		type_vocab_size=self.type_vocab_size				,		is_decoder=__A				,		initializer_range=self.initializer_range				,		)

												return config, input_ids, token_type_ids, attention_mask




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												a__       ,a__       ,a__       ,a__          =  config_and_inputs
												a__          =  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
												return config, inputs_dict





							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												a__       ,a__       ,a__       ,a__          =  config_and_inputs

												a__          =  True
												a__          =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]    )
												a__          =  ids_tensor([self.batch_size, self.seq_length]				,		vocab_size=2    )

												return (
												    config,
												    input_ids,
												    token_type_ids,
												    encoder_hidden_states,
												    encoder_attention_mask,
												)







@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =True

							_SCREAMING_SNAKE_CASE    =(
							    (
							        FlaxRobertaPreLayerNormModel,
							        FlaxRobertaPreLayerNormForCausalLM,
							        FlaxRobertaPreLayerNormForMaskedLM,
							        FlaxRobertaPreLayerNormForSequenceClassification,
							        FlaxRobertaPreLayerNormForTokenClassification,
							        FlaxRobertaPreLayerNormForMultipleChoice,
							        FlaxRobertaPreLayerNormForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormModelTester(self    )





							@slow
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												for model_class_name in self.all_model_classes:
																	a__          =  model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )
																	a__          =  model(np.ones((1, 1)    )    )
																	self.assertIsNotNone(__A    )







@require_flax
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )

												a__          =  np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]				,		dtype=jnp.intaa    )
												a__          =  model(__A    )[0]
												a__          =  [1, 11, 50265]
												self.assertEqual(list(output.shape    )				,		__A    )
												# compare the actual values for a slice.
												a__          =  np.array(
												    [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]]				,		dtype=np.floataa    )
												self.assertTrue(np.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )





							@slow
							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )

												a__          =  np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]				,		dtype=jnp.intaa    )
												a__          =  model(__A    )[0]
												# compare the actual values for a slice.
												a__          =  np.array(
												    [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]]				,		dtype=np.floataa    )
												self.assertTrue(np.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )


