






"""simple docstring"""






import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import (
      FocalNetBackbone,
      FocalNetForImageClassification,
      FocalNetForMaskedImageModeling,
      FocalNetModel,
  )
  from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor




class 							lowerCAmelCase__				:






      '''simple docstring'''

      def __init__(						self     :  str						,	lowercase_     :  str						,	lowercase_     :  Union[str, Any]=13						,	lowercase_     :  Dict=32						,	lowercase_     :  str=2						,	lowercase_     :  Union[str, Any]=3						,	lowercase_     :  List[str]=16						,	lowercase_     :  int=[32, 64, 128]						,	lowercase_     :  List[Any]=[1, 2, 1]						,	lowercase_     :  int=[2, 2, 4]						,	lowercase_     :  str=2						,	lowercase_     :  Optional[Any]=2.0						,	lowercase_     :  List[str]=True						,	lowercase_     :  List[str]=0.0						,	lowercase_     :  List[Any]=0.0						,	lowercase_     :  Tuple=0.1						,	lowercase_     :  Union[str, Any]="gelu"						,	lowercase_     :  int=False						,	lowercase_     :  Dict=True						,	lowercase_     :  int=0.02						,	lowercase_     :  Optional[Any]=1e-5						,	lowercase_     :  int=True						,	lowercase_     :  Union[str, Any]=None						,	lowercase_     :  List[str]=True						,	lowercase_     :  Tuple=10						,	lowercase_     :  Any=8						,	lowercase_     :  Any=["stage1", "stage2"]						,	lowercase_     :  str=[1, 2]						,	):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		parent
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		batch_size
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		image_size
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		patch_size
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		num_channels
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		embed_dim
          SCREAMING_SNAKE_CASE_      :  Dict    						=		hidden_sizes
          SCREAMING_SNAKE_CASE_      :  str    						=		depths
          SCREAMING_SNAKE_CASE_      :  Any    						=		num_heads
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		window_size
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		mlp_ratio
          SCREAMING_SNAKE_CASE_      :  Any    						=		qkv_bias
          SCREAMING_SNAKE_CASE_      :  Dict    						=		hidden_dropout_prob
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_      :  str    						=		drop_path_rate
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		hidden_act
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		use_absolute_embeddings
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		patch_norm
          SCREAMING_SNAKE_CASE_      :  Any    						=		layer_norm_eps
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		initializer_range
          SCREAMING_SNAKE_CASE_      :  str    						=		is_training
          SCREAMING_SNAKE_CASE_      :  Any    						=		scope
          SCREAMING_SNAKE_CASE_      :  str    						=		use_labels
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		type_sequence_label_size
          SCREAMING_SNAKE_CASE_      :  str    						=		encoder_stride
          SCREAMING_SNAKE_CASE_      :  Any    						=		out_features
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		out_indices
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          SCREAMING_SNAKE_CASE_      :  Any    						=		None
          if self.use_labels:
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		ids_tensor([self.batch_size]						,	self.type_sequence_label_size)

          SCREAMING_SNAKE_CASE_      :  str    						=		self.get_config()

          return config, pixel_values, labels
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          return FocalNetConfig(
              image_size=self.image_size						,	patch_size=self.patch_size						,	num_channels=self.num_channels						,	embed_dim=self.embed_dim						,	hidden_sizes=self.hidden_sizes						,	depths=self.depths						,	num_heads=self.num_heads						,	window_size=self.window_size						,	mlp_ratio=self.mlp_ratio						,	qkv_bias=self.qkv_bias						,	hidden_dropout_prob=self.hidden_dropout_prob						,	attention_probs_dropout_prob=self.attention_probs_dropout_prob						,	drop_path_rate=self.drop_path_rate						,	hidden_act=self.hidden_act						,	use_absolute_embeddings=self.use_absolute_embeddings						,	path_norm=self.patch_norm						,	layer_norm_eps=self.layer_norm_eps						,	initializer_range=self.initializer_range						,	encoder_stride=self.encoder_stride						,	out_features=self.out_features						,	out_indices=self.out_indices						,	)
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple						,	lowercase_     :  List[str]						,	lowercase_     :  Dict						,	lowercase_     :  Optional[int]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		FocalNetModel(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		model(lowercase_)

          SCREAMING_SNAKE_CASE_      :  Tuple    						=		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
          SCREAMING_SNAKE_CASE_      :  Any    						=		int(config.embed_dim * 2 ** (len(config.depths) - 1))

          self.parent.assertEqual(result.last_hidden_state.shape						,	(self.batch_size, expected_seq_len, expected_dim))
      def _SCREAMING_SNAKE_CASE (						self     :  int						,	lowercase_     :  Optional[Any]						,	lowercase_     :  List[Any]						,	lowercase_     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		FocalNetBackbone(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_      :  int    						=		model(lowercase_)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps)						,	len(config.out_features))
          self.parent.assertListEqual(list(result.feature_maps[0].shape)						,	[self.batch_size, self.image_size, 8, 8])

          # verify channels
          self.parent.assertEqual(len(model.channels)						,	len(config.out_features))
          self.parent.assertListEqual(model.channels						,	config.hidden_sizes[:-1])

          # verify backbone works with out_features=None
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		None
          SCREAMING_SNAKE_CASE_      :  str    						=		FocalNetBackbone(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_      :  str    						=		model(lowercase_)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps)						,	1)
          self.parent.assertListEqual(list(result.feature_maps[0].shape)						,	[self.batch_size, self.image_size * 2, 4, 4])

          # verify channels
          self.parent.assertEqual(len(model.channels)						,	1)
          self.parent.assertListEqual(model.channels						,	[config.hidden_sizes[-1]])
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[int]						,	lowercase_     :  Union[str, Any]						,	lowercase_     :  List[Any]						,	lowercase_     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		FocalNetForMaskedImageModeling(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		model(lowercase_)
          self.parent.assertEqual(
              result.reconstruction.shape						,	(self.batch_size, self.num_channels, self.image_size, self.image_size))

          # test greyscale images
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		1
          SCREAMING_SNAKE_CASE_      :  Any    						=		FocalNetForMaskedImageModeling(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          SCREAMING_SNAKE_CASE_      :  Dict    						=		model(lowercase_)
          self.parent.assertEqual(result.reconstruction.shape						,	(self.batch_size, 1, self.image_size, self.image_size))
      def _SCREAMING_SNAKE_CASE (						self     :  int						,	lowercase_     :  Tuple						,	lowercase_     :  str						,	lowercase_     :  str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  int    						=		self.type_sequence_label_size
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		FocalNetForImageClassification(lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		model(lowercase_						,	labels=lowercase_)
          self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.type_sequence_label_size))

          # test greyscale images
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		1
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		FocalNetForImageClassification(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_      :  int    						=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          SCREAMING_SNAKE_CASE_      :  str    						=		model(lowercase_)
          self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.type_sequence_label_size))



      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  int    						=		self.prepare_config_and_inputs()

          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[str]    						=		config_and_inputs
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		{'''pixel_values''': pixel_values}
          return config, inputs_dict




@require_torch
class 							lowerCAmelCase__				(			UpperCAmelCase__				,		UpperCAmelCase__				,		unittest.TestCase ):






      '''simple docstring'''

      __UpperCamelCase	 =  (
          (
              FocalNetModel,
              FocalNetForImageClassification,
              FocalNetForMaskedImageModeling,
              FocalNetBackbone,
          )
          if is_torch_available()
          else ()
      )
      __UpperCamelCase	 =  (
          {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
          if is_torch_available()
          else {}
      )
      __UpperCamelCase	 =  False

      __UpperCamelCase	 =  False
      __UpperCamelCase	 =  False
      __UpperCamelCase	 =  False
      __UpperCamelCase	 =  False
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		FocalNetModelTester(self)
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		ConfigTester(self						,	config_class=lowercase_						,	embed_dim=37						,	has_text_modality=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          self.create_and_test_config_common_properties()
          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 _SCREAMING_SNAKE_CASE (						self     :  List[str]):




          '''simple docstring'''


          return
      def _SCREAMING_SNAKE_CASE (						self     :  List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  int):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase_)
      @unittest.skip(reason='''FocalNet does not use inputs_embeds''')
      def _SCREAMING_SNAKE_CASE (						self     :  List[Any]):




          '''simple docstring'''


          pass
      @unittest.skip(reason='''FocalNet does not use feedforward chunking''')
      def _SCREAMING_SNAKE_CASE (						self     :  str):




          '''simple docstring'''


          pass
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes[:-1]:
              SCREAMING_SNAKE_CASE_      :  Any    						=		model_class(lowercase_)
              self.assertIsInstance(model.get_input_embeddings()						,	(nn.Module))
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowercase_						,	nn.Linear))
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes[:-1]:
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		model_class(lowercase_)
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		inspect.signature(model.forward)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		[*signature.parameters.keys()]

              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		['''pixel_values''']
              self.assertListEqual(arg_names[:1]						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  str						,	lowercase_     :  str						,	lowercase_     :  List[str]						,	lowercase_     :  Optional[int]						,	lowercase_     :  List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		model_class(lowercase_)
          model.to(lowercase_)
          model.eval()

          with torch.no_grad():
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		model(**self._prepare_for_class(lowercase_						,	lowercase_))

          SCREAMING_SNAKE_CASE_      :  List[str]    						=		outputs.hidden_states

          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		getattr(
              self.model_tester						,	'''expected_num_hidden_layers'''						,	len(self.model_tester.depths) + 1)
          self.assertEqual(len(lowercase_)						,	lowercase_)

          # FocalNet has a different seq_length
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		(
              config.patch_size
              if isinstance(config.patch_size						,	collections.abc.Iterable)
              else (config.patch_size, config.patch_size)
          )

          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

          self.assertListEqual(
              list(hidden_states[0].shape[-2:])						,	[num_patches, self.model_tester.embed_dim]						,	)

          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		outputs.reshaped_hidden_states
          self.assertEqual(len(lowercase_)						,	lowercase_)

          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[Any]    						=		reshaped_hidden_states[0].shape
          SCREAMING_SNAKE_CASE_      :  int    						=		(
              reshaped_hidden_states[0].view(lowercase_						,	lowercase_						,	height * width).permute(0						,	2						,	1)
          )
          self.assertListEqual(
              list(reshaped_hidden_states.shape[-2:])						,	[num_patches, self.model_tester.embed_dim]						,	)
      def _SCREAMING_SNAKE_CASE (						self     :  List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  Any    						=		self.model_tester.prepare_config_and_inputs_for_common()

          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size						,	collections.abc.Iterable)
              else (self.model_tester.image_size, self.model_tester.image_size)
          )

          for model_class in self.all_model_classes[:-1]:
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		True
              self.check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_						,	lowercase_)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE_      :  List[str]    						=		True

              self.check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		self.model_tester.prepare_config_and_inputs_for_common()
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		3

          SCREAMING_SNAKE_CASE_      :  Any    						=		(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size						,	collections.abc.Iterable)
              else (self.model_tester.image_size, self.model_tester.image_size)
          )
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		(
              config.patch_size
              if isinstance(config.patch_size						,	collections.abc.Iterable)
              else (config.patch_size, config.patch_size)
          )

          SCREAMING_SNAKE_CASE_      :  Any    						=		image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

          for model_class in self.all_model_classes[:-1]:
              SCREAMING_SNAKE_CASE_      :  Any    						=		True
              self.check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_						,	(padded_height, padded_width))

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE_      :  Dict    						=		True
              self.check_hidden_states_output(lowercase_						,	lowercase_						,	lowercase_						,	(padded_height, padded_width))
      @slow
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[int]):




          '''simple docstring'''


          for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		FocalNetModel.from_pretrained(lowercase_)
              self.assertIsNotNone(lowercase_)



      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  Dict    						=		self.model_tester.prepare_config_and_inputs_for_common()

          SCREAMING_SNAKE_CASE_      :  Dict    						=		_config_zero_init(lowercase_)
          for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_      :  List[str]    						=		model_class(config=lowercase_)
              for name, param in model.named_parameters():
                  if "embeddings" not in name and param.requires_grad:
                      self.assertIn(
                          ((param.data.mean() * 1e9).round() / 1e9).item()						,	[0.0, 1.0]						,	msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,	)




@require_vision
@require_torch
class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      @cached_property
      def _SCREAMING_SNAKE_CASE (						self     :  int):




          '''simple docstring'''


          return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny''') if is_vision_available() else None



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




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny''').to(lowercase_)
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.default_image_processor

          SCREAMING_SNAKE_CASE_      :  List[str]    						=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
          SCREAMING_SNAKE_CASE_      :  str    						=		image_processor(images=lowercase_						,	return_tensors='''pt''').to(lowercase_)

          # forward pass
          with torch.no_grad():
              SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		model(**lowercase_)

          # verify the logits
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape						,	lowercase_)
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		torch.tensor([0.21_66, -0.43_68, 0.21_91]).to(lowercase_)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]						,	lowercase_						,	atol=1e-4))
          self.assertTrue(outputs.logits.argmax(dim=-1).item()						,	281)




@require_torch
class 							lowerCAmelCase__				(			UpperCAmelCase__				,		unittest.TestCase ):






      '''simple docstring'''

      __UpperCamelCase	 =  (FocalNetBackbone,) if is_torch_available() else ()
      __UpperCamelCase	 =  FocalNetConfig

      __UpperCamelCase	 =  False
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		FocalNetModelTester(self)










"""simple docstring"""






import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test




class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      @parameterized.expand([(None,), ('''foo.json''',)])
      def _SCREAMING_SNAKE_CASE (						self     :  Dict						,	lowercase_     :  Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[str]    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	bad_words_ids=[[1, 2, 3], [4, 5]]						,	)
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(lowercase_						,	config_name=lowercase_)
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig.from_pretrained(lowercase_						,	config_name=lowercase_)

          # Checks parameters that were specified
          self.assertEqual(loaded_config.do_sample						,	lowercase_)
          self.assertEqual(loaded_config.temperature						,	0.7)
          self.assertEqual(loaded_config.length_penalty						,	1.0)
          self.assertEqual(loaded_config.bad_words_ids						,	[[1, 2, 3], [4, 5]])

          # Checks parameters that were not specified (defaults)
          self.assertEqual(loaded_config.top_k						,	50)
          self.assertEqual(loaded_config.max_length						,	20)
          self.assertEqual(loaded_config.max_time						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		AutoConfig.from_pretrained('''gpt2''')
          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig.from_model_config(lowercase_)
          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig()

          # The generation config has loaded a few non-default parameters from the model config
          self.assertNotEqual(lowercase_						,	lowercase_)

          # One of those parameters is eos_token_id -- check if it matches
          self.assertNotEqual(generation_config_from_model.eos_token_id						,	default_generation_config.eos_token_id)
          self.assertEqual(generation_config_from_model.eos_token_id						,	model_config.eos_token_id)
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		GenerationConfig()
          SCREAMING_SNAKE_CASE_      :  Any    						=		{
              '''max_new_tokens''': 1024,
              '''foo''': '''bar''',
          }
          SCREAMING_SNAKE_CASE_      :  str    						=		copy.deepcopy(lowercase_)
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		generation_config.update(**lowercase_)

          # update_kwargs was not modified (no side effects)
          self.assertEqual(lowercase_						,	lowercase_)

          # update_kwargs was used to update the config on valid attributes
          self.assertEqual(generation_config.max_new_tokens						,	1024)

          # `.update()` returns a dictionary of unused kwargs
          self.assertEqual(lowercase_						,	{'''foo''': '''bar'''})
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		GenerationConfig()
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		'''bar'''

          with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir:
              generation_config.save_pretrained(lowercase_)

              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		GenerationConfig.from_pretrained(lowercase_)
          # update_kwargs was used to update the config on valid attributes
          self.assertEqual(new_config.foo						,	'''bar''')

          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		GenerationConfig.from_model_config(lowercase_)
          assert not hasattr(lowercase_						,	'''foo''')  # no new kwargs should be initialized if from config



      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig()
          self.assertEqual(default_config.temperature						,	1.0)
          self.assertEqual(default_config.do_sample						,	lowercase_)
          self.assertEqual(default_config.num_beams						,	1)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	bad_words_ids=[[1, 2, 3], [4, 5]]						,	)
          self.assertEqual(config.temperature						,	0.7)
          self.assertEqual(config.do_sample						,	lowercase_)
          self.assertEqual(config.num_beams						,	1)

          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(lowercase_)
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig.from_pretrained(lowercase_						,	temperature=1.0)

          self.assertEqual(loaded_config.temperature						,	1.0)
          self.assertEqual(loaded_config.do_sample						,	lowercase_)
          self.assertEqual(loaded_config.num_beams						,	1)  # default value




@is_staging_test
class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      @classmethod
      def _SCREAMING_SNAKE_CASE (						cls     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		TOKEN
          HfFolder.save_token(lowercase_)
      @classmethod
      def _SCREAMING_SNAKE_CASE (						cls     :  List[str]):




          '''simple docstring'''


          try:
              delete_repo(token=cls._token						,	repo_id='''test-generation-config''')
          except HTTPError:
              pass

          try:
              delete_repo(token=cls._token						,	repo_id='''valid_org/test-generation-config-org''')
          except HTTPError:
              pass
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	)
          config.push_to_hub('''test-generation-config'''						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig.from_pretrained(F'{USER}/test-generation-config')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))

        # Reset repo
          delete_repo(token=self._token						,	repo_id='''test-generation-config''')

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(
                  lowercase_						,	repo_id='''test-generation-config'''						,	push_to_hub=lowercase_						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		GenerationConfig.from_pretrained(F'{USER}/test-generation-config')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))



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




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Dict    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	)
          config.push_to_hub('''valid_org/test-generation-config-org'''						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Any    						=		GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))

        # Reset repo
          delete_repo(token=self._token						,	repo_id='''valid_org/test-generation-config-org''')

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(
                  lowercase_						,	repo_id='''valid_org/test-generation-config-org'''						,	push_to_hub=lowercase_						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Any    						=		GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))


