





"""simple docstring"""


import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
    from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder




def   snake_case		(     UpperCamelCase__       :						Tuple			,				UpperCamelCase__       :						Optional[Any]			,				UpperCamelCase__       :						Tuple			,				UpperCamelCase__       :						Dict=None			,				UpperCamelCase__       :						str=None			,				UpperCamelCase__       :						List[Any]=None			,				UpperCamelCase__       :						int=None			,				UpperCamelCase__       :						Any=None			,				)   ->      Optional[Any]:
      if attention_mask is None:
            lowerCamelCase					:					Any        =	input_ids.ne(config.pad_token_id    )
      if decoder_attention_mask is None:
            lowerCamelCase					:					int        =	decoder_input_ids.ne(config.pad_token_id    )
      if head_mask is None:
            lowerCamelCase					:					List[Any]        =	torch.ones(config.encoder_layers			,				config.encoder_attention_heads			,				device=UpperCamelCase__    )
      if decoder_head_mask is None:
            lowerCamelCase					:					List[str]        =	torch.ones(config.decoder_layers			,				config.decoder_attention_heads			,				device=UpperCamelCase__    )
      if cross_attn_head_mask is None:
            lowerCamelCase					:					List[Any]        =	torch.ones(config.decoder_layers			,				config.decoder_attention_heads			,				device=UpperCamelCase__    )
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": attention_mask,
          "head_mask": head_mask,
          "decoder_head_mask": decoder_head_mask,
          "cross_attn_head_mask": cross_attn_head_mask,
      }


class 			A__	:


     """simple docstring"""

     def __init__(	self:						Dict     ,		__a:						Any     ,		__a:						Optional[int]=13     ,		__a:						Tuple=7     ,		__a:						Optional[int]=True     ,		__a:						Optional[int]=False     ,		__a:						List[str]=99     ,		__a:						str=16     ,		__a:						str=2     ,		__a:						List[str]=4     ,		__a:						Union[str, Any]=4     ,		__a:						Dict="relu"     ,		__a:						int=0.1     ,		__a:						str=0.1     ,		__a:						Union[str, Any]=0.0     ,		__a:						Optional[Any]=0.0     ,		__a:						List[Any]=20     ,		__a:						str=2     ,		__a:						int=1     ,		__a:						Optional[Any]=0     ,		)->    Optional[int]:
           lowerCamelCase					:					Any        =	parent
           lowerCamelCase					:					Any        =	batch_size
           lowerCamelCase					:					List[str]        =	seq_length
           lowerCamelCase					:					Optional[int]        =	is_training
           lowerCamelCase					:					str        =	use_labels
           lowerCamelCase					:					Tuple        =	vocab_size
           lowerCamelCase					:					Optional[Any]        =	hidden_size
           lowerCamelCase					:					Tuple        =	num_hidden_layers
           lowerCamelCase					:					List[Any]        =	num_attention_heads
           lowerCamelCase					:					Tuple        =	intermediate_size
           lowerCamelCase					:					str        =	hidden_act
           lowerCamelCase					:					Optional[Any]        =	hidden_dropout_prob
           lowerCamelCase					:					int        =	attention_probs_dropout_prob
           lowerCamelCase					:					Optional[int]        =	encoder_layerdrop
           lowerCamelCase					:					Dict        =	decoder_layerdrop
           lowerCamelCase					:					List[Any]        =	max_position_embeddings
           lowerCamelCase					:					List[str]        =	eos_token_id
           lowerCamelCase					:					List[str]        =	pad_token_id
           lowerCamelCase					:					Tuple        =	bos_token_id

     def 		a__						(	self:						List[Any]	)->    Tuple:
           lowerCamelCase					:					Tuple        =	ids_tensor([self.batch_size, self.seq_length]     ,		self.vocab_size	)
           lowerCamelCase					:					List[str]        =	self.eos_token_id  # Eos Token
           lowerCamelCase					:					str        =	ids_tensor([self.batch_size, self.seq_length]     ,		self.vocab_size	)

           # we need to clamp the input ids here to avoid having pad token in between
           # this is because for M2M100 the position_ids are prepared such that
           # all pad tokens have pos id = 2 and rest are between 2..seq_length
           # and the seq_length here is seq_length - num_pad_tokens
           # but when using past, there is no way of knowing if the past input ids had
           # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
           # position_ids being off by num_pad_tokens in past input
           lowerCamelCase					:					List[str]        =	input_ids.clamp(self.pad_token_id + 1	)
           lowerCamelCase					:					str        =	decoder_input_ids.clamp(self.pad_token_id + 1	)

           lowerCamelCase					:					List[str]        =	self.get_config()
           lowerCamelCase					:					Tuple        =	prepare_mam_aaa_inputs_dict(__a     ,		__a     ,		__a	)
           return config, inputs_dict

     def 		a__						(	self:						str	)->    int:
           return MaMaaaConfig(
               vocab_size=self.vocab_size     ,		d_model=self.hidden_size     ,		encoder_layers=self.num_hidden_layers     ,		decoder_layers=self.num_hidden_layers     ,		encoder_attention_heads=self.num_attention_heads     ,		decoder_attention_heads=self.num_attention_heads     ,		encoder_ffn_dim=self.intermediate_size     ,		decoder_ffn_dim=self.intermediate_size     ,		dropout=self.hidden_dropout_prob     ,		attention_dropout=self.attention_probs_dropout_prob     ,		encoder_layerdrop=self.encoder_layerdrop     ,		decoder_layerdrop=self.decoder_layerdrop     ,		max_position_embeddings=self.max_position_embeddings     ,		eos_token_id=self.eos_token_id     ,		bos_token_id=self.bos_token_id     ,		pad_token_id=self.pad_token_id     ,		)

     def 		a__						(	self:						List[str]	)->    Optional[Any]:
           lowerCamelCase					:					List[str]        =	self.prepare_config_and_inputs()
           return config, inputs_dict

     def 		a__						(	self:						Any     ,		__a:						Optional[int]     ,		__a:						List[Any]	)->    List[str]:
           lowerCamelCase					:					Dict        =	MaMaaaModel(config=__a	).get_decoder().to(__a	).eval()
           lowerCamelCase					:					Any        =	inputs_dict["""input_ids"""]
           lowerCamelCase					:					Union[str, Any]        =	inputs_dict["""attention_mask"""]
           lowerCamelCase					:					Dict        =	inputs_dict["""head_mask"""]

           # first forward pass
           lowerCamelCase					:					Dict        =	model(__a     ,		attention_mask=__a     ,		head_mask=__a     ,		use_cache=__a	)

           lowerCamelCase					:					Dict        =	outputs.to_tuple()

           # create hypothetical multiple next token and extent to next_input_ids
           lowerCamelCase					:					Dict        =	ids_tensor((self.batch_size, 3)     ,		config.vocab_size	)
           lowerCamelCase					:					Tuple        =	ids_tensor((self.batch_size, 3)     ,		2	)

           # append to next input_ids and
           lowerCamelCase					:					Optional[int]        =	torch.cat([input_ids, next_tokens]     ,		dim=-1	)
           lowerCamelCase					:					Optional[int]        =	torch.cat([attention_mask, next_attn_mask]     ,		dim=-1	)

           lowerCamelCase					:					Tuple        =	model(__a     ,		attention_mask=__a	)["""last_hidden_state"""]
           lowerCamelCase					:					Optional[Any]        =	model(__a     ,		attention_mask=__a     ,		past_key_values=__a	)[
               """last_hidden_state"""
           ]

           # select random slice
           lowerCamelCase					:					List[Any]        =	ids_tensor((1,)     ,		output_from_past.shape[-1]	).item()
           lowerCamelCase					:					Dict        =	output_from_no_past[:, -3:, random_slice_idx].detach()
           lowerCamelCase					:					Any        =	output_from_past[:, :, random_slice_idx].detach()

           self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]	)

           # test that outputs are equal for slice
           self.parent.assertTrue(torch.allclose(__a     ,		__a     ,		atol=1e-2	)	)







     def 		a__						(	self:						Union[str, Any]     ,		__a:						str     ,		__a:						Dict	)->    Any:
           lowerCamelCase					:					Union[str, Any]        =	MaMaaaModel(config=__a	).to(__a	).eval()
           lowerCamelCase					:					Any        =	model(**__a	)

           lowerCamelCase					:					Any        =	outputs.encoder_last_hidden_state
           lowerCamelCase					:					Dict        =	outputs.last_hidden_state

           with tempfile.TemporaryDirectory() as tmpdirname:
                 lowerCamelCase					:					List[Any]        =	model.get_encoder()
                 encoder.save_pretrained(__a	)
                 lowerCamelCase					:					Union[str, Any]        =	MaMaaaEncoder.from_pretrained(__a	).to(__a	)

           lowerCamelCase					:					List[Any]        =	encoder(inputs_dict["""input_ids"""]     ,		attention_mask=inputs_dict["""attention_mask"""]	)[
               0
           ]

           self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3	)

           with tempfile.TemporaryDirectory() as tmpdirname:
                 lowerCamelCase					:					Dict        =	model.get_decoder()
                 decoder.save_pretrained(__a	)
                 lowerCamelCase					:					Dict        =	MaMaaaDecoder.from_pretrained(__a	).to(__a	)

           lowerCamelCase					:					int        =	decoder(
               input_ids=inputs_dict["""decoder_input_ids"""]     ,		attention_mask=inputs_dict["""decoder_attention_mask"""]     ,		encoder_hidden_states=__a     ,		encoder_attention_mask=inputs_dict["""attention_mask"""]     ,		)[0]

           self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3	)


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


     """simple docstring"""
     snake_case__	:					str													=(
         (
             MaMaaaModel,
             MaMaaaForConditionalGeneration,
         )
         if is_torch_available()
         else ()
     )
     snake_case__	:					Optional[int]													=(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
     snake_case__	:					int													=(
         {
             '''conversational''': MaMaaaForConditionalGeneration,
             '''feature-extraction''': MaMaaaModel,
             '''summarization''': MaMaaaForConditionalGeneration,
             '''text2text-generation''': MaMaaaForConditionalGeneration,
             '''translation''': MaMaaaForConditionalGeneration,
         }
         if is_torch_available()
         else {}
     )
     snake_case__	:					List[Any]													=True
     snake_case__	:					Optional[Any]													=True
     snake_case__	:					Dict													=False
     snake_case__	:					Optional[Any]													=False

     def 		a__						(	self:						Tuple     ,		__a:						Dict     ,		__a:						List[Any]     ,		__a:						Union[str, Any]     ,		__a:						Any     ,		__a:						Optional[Any]	)->    Dict:
           if pipeline_test_casse_name == "TranslationPipelineTests":
                 # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
                 # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
                 return True

           return False

     def 		a__						(	self:						Any	)->    List[str]:
           lowerCamelCase					:					Any        =	MaMaaaModelTester(self	)
           lowerCamelCase					:					Union[str, Any]        =	ConfigTester(self     ,		config_class=__a	)

     def 		a__						(	self:						str	)->    str:
           self.config_tester.run_common_tests()

     def 		a__						(	self:						Optional[int]	)->    Any:
           lowerCamelCase					:					List[Any]        =	self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                 lowerCamelCase					:					Optional[Any]        =	model_class(__a	)

                 with tempfile.TemporaryDirectory() as tmpdirname:
                       model.save_pretrained(__a	)
                       lowerCamelCase					:					str        =	model_class.from_pretrained(__a     ,		output_loading_info=__a	)
                 self.assertEqual(info["""missing_keys"""]     ,		[]	)

     def 		a__						(	self:						Dict	)->    Tuple:
           lowerCamelCase					:					Dict        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a	)

     def 		a__						(	self:						Union[str, Any]	)->    str:
           lowerCamelCase					:					str        =	self.model_tester.prepare_config_and_inputs_for_common()
           self.model_tester.check_encoder_decoder_model_standalone(*__a	)

     def 		a__						(	self:						Tuple	)->    Any:
           lowerCamelCase					:					Union[str, Any]        =	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                 lowerCamelCase					:					Tuple        =	model_class(__a	)
                 model.to(__a	)
                 model.eval()

                 lowerCamelCase					:					Tuple        =	copy.deepcopy(self._prepare_for_class(__a     ,		__a	)	)

                 if not self.is_encoder_decoder:
                       lowerCamelCase					:					str        =	inputs["""input_ids"""]
                       del inputs["input_ids"]
                 else:
                       lowerCamelCase					:					List[Any]        =	inputs["""input_ids"""]
                       lowerCamelCase					:					int        =	inputs.get("""decoder_input_ids"""     ,		__a	)
                       del inputs["input_ids"]
                       inputs.pop("""decoder_input_ids"""     ,		__a	)

                 lowerCamelCase					:					Dict        =	model.get_input_embeddings()
                 if not self.is_encoder_decoder:
                       lowerCamelCase					:					Any        =	wte(__a	)
                 else:
                       lowerCamelCase					:					Optional[int]        =	wte(__a	)
                       lowerCamelCase					:					Tuple        =	wte(__a	)

                 with torch.no_grad():
                       model(**__a	)[0]







     def 		a__						(	self:						List[str]	)->    List[str]:
           lowerCamelCase					:					Optional[int]        =	self.model_tester.prepare_config_and_inputs()
           lowerCamelCase					:					List[str]        =	input_dict["""input_ids"""]
           lowerCamelCase					:					int        =	input_ids.ne(1	).to(__a	)
           lowerCamelCase					:					Any        =	MaMaaaForConditionalGeneration(__a	).eval().to(__a	)
           if torch_device == "cuda":
                 model.half()
           model.generate(__a     ,		attention_mask=__a	)
           model.generate(num_beams=4     ,		do_sample=__a     ,		early_stopping=__a     ,		num_return_sequences=3	)




def   snake_case		(     UpperCamelCase__       :						Dict    )   ->      Optional[Any]:
      return torch.tensor(UpperCamelCase__			,				dtype=torch.long			,				device=UpperCamelCase__    )


__lowerCamelCase      :List[Any]	    =		1e-4






@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 			A__	(						unittest.TestCase):


     """simple docstring"""

     @cached_property
     def 		a__						(	self:						Any	)->    str:
           return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""	)

     def 		a__						(	self:						Optional[Any]	)->    int:
           lowerCamelCase					:					Dict        =	MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""	).to(__a	)
           lowerCamelCase					:					List[Any]        =	_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]	)
           lowerCamelCase					:					int        =	_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]	)
           lowerCamelCase					:					Any        =	prepare_mam_aaa_inputs_dict(model.config     ,		__a     ,		__a	)
           with torch.no_grad():
                 lowerCamelCase					:					Optional[Any]        =	model(**__a	)[0]
           lowerCamelCase					:					List[Any]        =	torch.Size((1, 11, 1_024)	)
           self.assertEqual(output.shape     ,		__a	)
           # change to expected output here
           lowerCamelCase					:					int        =	torch.tensor(
               [[-0.77_80, -0.16_76, 0.10_38], [-6.75_56, -1.39_92, 0.05_67], [-7.53_83, -0.59_20, -0.27_79]]     ,		device=__a	)
           self.assertTrue(torch.allclose(output[:, :3, :3]     ,		__a     ,		atol=__a	)	)

     def 		a__						(	self:						Optional[Any]	)->    Optional[Any]:
           lowerCamelCase					:					Optional[Any]        =	MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""	).to(__a	)

           # change to intended input
           lowerCamelCase					:					Union[str, Any]        =	_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]	)
           lowerCamelCase					:					Optional[Any]        =	_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]	)
           lowerCamelCase					:					Any        =	prepare_mam_aaa_inputs_dict(model.config     ,		__a     ,		__a	)
           with torch.no_grad():
                 lowerCamelCase					:					str        =	model(**__a	)[0]
           lowerCamelCase					:					Dict        =	torch.Size((1, 11, model.config.vocab_size)	)
           self.assertEqual(output.shape     ,		__a	)
           # change to expected output here
           lowerCamelCase					:					str        =	torch.tensor(
               [[-1.04_48, -1.04_11, 3.79_92], [-3.21_91, -3.23_86, -1.34_51], [-3.62_10, -3.59_93, 0.49_25]]     ,		device=__a	)
           self.assertTrue(torch.allclose(output[:, :3, :3]     ,		__a     ,		atol=__a	)	)







     def 		a__						(	self:						str	)->    Optional[int]:
           lowerCamelCase					:					Union[str, Any]        =	MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""	).to(__a	)
           lowerCamelCase					:					Any        =	MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""     ,		src_lang="""fr"""     ,		tgt_lang="""en"""	)

           lowerCamelCase					:					List[str]        =	[
               """L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
               """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
               """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"""
               """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"""
               """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""",
           ]

           # The below article tests that we don't add any hypotheses outside of the top n_beams
           lowerCamelCase					:					int        =	tokenizer(__a     ,		padding=__a     ,		return_tensors="""pt"""	)

           lowerCamelCase					:					str        =	model.generate(
               input_ids=dct["""input_ids"""].to(__a	)     ,		attention_mask=dct["""attention_mask"""].to(__a	)     ,		num_beams=5     ,		forced_bos_token_id=tokenizer.get_lang_id("""en"""	)     ,		)

           lowerCamelCase					:					Tuple        =	[
               """The NSA case highlights the total absence of intelligence debate""",
               """I think there are two levels of response from the French government.""",
               """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."""
               """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"""
               """ communications in France.""",
           ]

           lowerCamelCase					:					Optional[int]        =	tokenizer.batch_decode(
               hypotheses_batch.tolist()     ,		clean_up_tokenization_spaces=__a     ,		skip_special_tokens=__a	)
           assert generated == expected_en








"""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 			A__	:


     """simple docstring"""

     def __init__(	self:						List[Any]     ,		__a:						List[str]     ,		__a:						Optional[int]=13     ,		__a:						List[str]=32     ,		__a:						int=2     ,		__a:						List[str]=3     ,		__a:						Union[str, Any]=16     ,		__a:						int=[32, 64, 128]     ,		__a:						Optional[Any]=[1, 2, 1]     ,		__a:						Optional[int]=[2, 2, 4]     ,		__a:						Tuple=2     ,		__a:						Dict=2.0     ,		__a:						List[str]=True     ,		__a:						Optional[Any]=0.0     ,		__a:						Any=0.0     ,		__a:						List[Any]=0.1     ,		__a:						List[str]="gelu"     ,		__a:						Tuple=False     ,		__a:						Union[str, Any]=True     ,		__a:						Optional[int]=0.02     ,		__a:						Tuple=1e-5     ,		__a:						int=True     ,		__a:						List[Any]=None     ,		__a:						Optional[int]=True     ,		__a:						Dict=10     ,		__a:						List[str]=8     ,		__a:						Any=["stage1", "stage2"]     ,		__a:						Union[str, Any]=[1, 2]     ,		)->    Dict:
           lowerCamelCase					:					Dict        =	parent
           lowerCamelCase					:					Optional[Any]        =	batch_size
           lowerCamelCase					:					Union[str, Any]        =	image_size
           lowerCamelCase					:					Optional[int]        =	patch_size
           lowerCamelCase					:					Any        =	num_channels
           lowerCamelCase					:					Any        =	embed_dim
           lowerCamelCase					:					Dict        =	hidden_sizes
           lowerCamelCase					:					List[Any]        =	depths
           lowerCamelCase					:					Tuple        =	num_heads
           lowerCamelCase					:					List[Any]        =	window_size
           lowerCamelCase					:					str        =	mlp_ratio
           lowerCamelCase					:					str        =	qkv_bias
           lowerCamelCase					:					str        =	hidden_dropout_prob
           lowerCamelCase					:					Dict        =	attention_probs_dropout_prob
           lowerCamelCase					:					Tuple        =	drop_path_rate
           lowerCamelCase					:					Dict        =	hidden_act
           lowerCamelCase					:					Tuple        =	use_absolute_embeddings
           lowerCamelCase					:					List[str]        =	patch_norm
           lowerCamelCase					:					List[str]        =	layer_norm_eps
           lowerCamelCase					:					str        =	initializer_range
           lowerCamelCase					:					Tuple        =	is_training
           lowerCamelCase					:					int        =	scope
           lowerCamelCase					:					Union[str, Any]        =	use_labels
           lowerCamelCase					:					List[str]        =	type_sequence_label_size
           lowerCamelCase					:					str        =	encoder_stride
           lowerCamelCase					:					List[str]        =	out_features
           lowerCamelCase					:					Optional[int]        =	out_indices

     def 		a__						(	self:						Optional[Any]	)->    Union[str, Any]:
           lowerCamelCase					:					Union[str, Any]        =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

           lowerCamelCase					:					str        =	None
           if self.use_labels:
                 lowerCamelCase					:					List[str]        =	ids_tensor([self.batch_size]     ,		self.type_sequence_label_size	)

           lowerCamelCase					:					str        =	self.get_config()

           return config, pixel_values, labels

     def 		a__						(	self:						List[Any]	)->    Optional[int]:
           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 		a__						(	self:						Tuple     ,		__a:						Optional[int]     ,		__a:						Optional[int]     ,		__a:						Optional[int]	)->    List[str]:
           lowerCamelCase					:					Tuple        =	FocalNetModel(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					Tuple        =	model(__a	)

           lowerCamelCase					:					Any        =	((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths	) - 1))
           lowerCamelCase					:					List[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 		a__						(	self:						Optional[int]     ,		__a:						Dict     ,		__a:						Tuple     ,		__a:						List[Any]	)->    int:
           lowerCamelCase					:					List[Any]        =	FocalNetBackbone(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					Optional[Any]        =	model(__a	)

           # 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
           lowerCamelCase					:					Dict        =	None
           lowerCamelCase					:					Dict        =	FocalNetBackbone(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					Any        =	model(__a	)

           # 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 		a__						(	self:						Optional[int]     ,		__a:						Optional[int]     ,		__a:						Optional[int]     ,		__a:						Optional[int]	)->    List[str]:
           lowerCamelCase					:					Tuple        =	FocalNetForMaskedImageModeling(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					List[str]        =	model(__a	)
           self.parent.assertEqual(
               result.reconstruction.shape     ,		(self.batch_size, self.num_channels, self.image_size, self.image_size)	)

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

           lowerCamelCase					:					str        =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
           lowerCamelCase					:					Tuple        =	model(__a	)
           self.parent.assertEqual(result.reconstruction.shape     ,		(self.batch_size, 1, self.image_size, self.image_size)	)

     def 		a__						(	self:						str     ,		__a:						Optional[Any]     ,		__a:						Optional[Any]     ,		__a:						Tuple	)->    str:
           lowerCamelCase					:					Optional[Any]        =	self.type_sequence_label_size
           lowerCamelCase					:					Optional[Any]        =	FocalNetForImageClassification(__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					List[str]        =	model(__a     ,		labels=__a	)
           self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.type_sequence_label_size)	)

           # test greyscale images
           lowerCamelCase					:					int        =	1
           lowerCamelCase					:					List[Any]        =	FocalNetForImageClassification(__a	)
           model.to(__a	)
           model.eval()

           lowerCamelCase					:					Union[str, Any]        =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
           lowerCamelCase					:					Optional[Any]        =	model(__a	)
           self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.type_sequence_label_size)	)







     def 		a__						(	self:						int	)->    Optional[int]:
           lowerCamelCase					:					str        =	self.prepare_config_and_inputs()

           lowerCamelCase     ,			lowerCamelCase     ,			lowerCamelCase					:					Optional[int]        =	config_and_inputs
           lowerCamelCase					:					List[Any]        =	{"""pixel_values""": pixel_values}
           return config, inputs_dict


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


     """simple docstring"""
     snake_case__	:					List[str]													=(
         (
             FocalNetModel,
             FocalNetForImageClassification,
             FocalNetForMaskedImageModeling,
             FocalNetBackbone,
         )
         if is_torch_available()
         else ()
     )
     snake_case__	:					Optional[int]													=(
         {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
         if is_torch_available()
         else {}
     )
     snake_case__	:					Tuple													=False

     snake_case__	:					Dict													=False
     snake_case__	:					Dict													=False
     snake_case__	:					Tuple													=False
     snake_case__	:					Optional[int]													=False

     def 		a__						(	self:						Union[str, Any]	)->    Optional[int]:
           lowerCamelCase					:					List[str]        =	FocalNetModelTester(self	)
           lowerCamelCase					:					Optional[Any]        =	ConfigTester(self     ,		config_class=__a     ,		embed_dim=37     ,		has_text_modality=__a	)

     def 		a__						(	self:						List[str]	)->    List[str]:
           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 		a__						(	self:						List[str]	)->    Union[str, Any]:
           return

     def 		a__						(	self:						Tuple	)->    Tuple:
           lowerCamelCase					:					Dict        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__a	)

     def 		a__						(	self:						List[Any]	)->    Dict:
           lowerCamelCase					:					int        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*__a	)

     def 		a__						(	self:						List[Any]	)->    Tuple:
           lowerCamelCase					:					Dict        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*__a	)

     def 		a__						(	self:						List[str]	)->    Dict:
           lowerCamelCase					:					Tuple        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__a	)

     @unittest.skip(reason="""FocalNet does not use inputs_embeds"""	)
     def 		a__						(	self:						Optional[Any]	)->    str:
           pass

     @unittest.skip(reason="""FocalNet does not use feedforward chunking"""	)
     def 		a__						(	self:						Optional[Any]	)->    Dict:
           pass

     def 		a__						(	self:						Optional[Any]	)->    Dict:
           lowerCamelCase     ,			lowerCamelCase					:					List[str]        =	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes[:-1]:
                 lowerCamelCase					:					Any        =	model_class(__a	)
                 self.assertIsInstance(model.get_input_embeddings()     ,		(nn.Module)	)
                 lowerCamelCase					:					Dict        =	model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(__a     ,		nn.Linear	)	)

     def 		a__						(	self:						Tuple	)->    Optional[int]:
           lowerCamelCase     ,			lowerCamelCase					:					List[str]        =	self.model_tester.prepare_config_and_inputs_for_common()

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

                 lowerCamelCase					:					List[Any]        =	["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]     ,		__a	)

     def 		a__						(	self:						str     ,		__a:						Union[str, Any]     ,		__a:						int     ,		__a:						Tuple     ,		__a:						List[str]	)->    Union[str, Any]:
           lowerCamelCase					:					List[Any]        =	model_class(__a	)
           model.to(__a	)
           model.eval()

           with torch.no_grad():
                 lowerCamelCase					:					List[str]        =	model(**self._prepare_for_class(__a     ,		__a	)	)

           lowerCamelCase					:					List[str]        =	outputs.hidden_states

           lowerCamelCase					:					Tuple        =	getattr(
               self.model_tester     ,		"""expected_num_hidden_layers"""     ,		len(self.model_tester.depths	) + 1	)
           self.assertEqual(len(__a	)     ,		__a	)

           # FocalNet has a different seq_length
           lowerCamelCase					:					Tuple        =	(
               config.patch_size
               if isinstance(config.patch_size     ,		collections.abc.Iterable	)
               else (config.patch_size, config.patch_size)
           )

           lowerCamelCase					:					Dict        =	(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]     ,		)

           lowerCamelCase					:					Optional[Any]        =	outputs.reshaped_hidden_states
           self.assertEqual(len(__a	)     ,		__a	)

           lowerCamelCase     ,			lowerCamelCase     ,			lowerCamelCase     ,			lowerCamelCase					:					Optional[int]        =	reshaped_hidden_states[0].shape
           lowerCamelCase					:					Tuple        =	(
               reshaped_hidden_states[0].view(__a     ,		__a     ,		height * width	).permute(0     ,		2     ,		1	)
           )
           self.assertListEqual(
               list(reshaped_hidden_states.shape[-2:]	)     ,		[num_patches, self.model_tester.embed_dim]     ,		)

     def 		a__						(	self:						Any	)->    Any:
           lowerCamelCase     ,			lowerCamelCase					:					str        =	self.model_tester.prepare_config_and_inputs_for_common()

           lowerCamelCase					:					Union[str, 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)
           )

           for model_class in self.all_model_classes[:-1]:
                 lowerCamelCase					:					List[str]        =	True
                 self.check_hidden_states_output(__a     ,		__a     ,		__a     ,		__a	)

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

                 self.check_hidden_states_output(__a     ,		__a     ,		__a     ,		__a	)

     def 		a__						(	self:						str	)->    Union[str, Any]:
           lowerCamelCase     ,			lowerCamelCase					:					Tuple        =	self.model_tester.prepare_config_and_inputs_for_common()
           lowerCamelCase					:					List[str]        =	3

           lowerCamelCase					:					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)
           )
           lowerCamelCase					:					Optional[int]        =	(
               config.patch_size
               if isinstance(config.patch_size     ,		collections.abc.Iterable	)
               else (config.patch_size, config.patch_size)
           )

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

           for model_class in self.all_model_classes[:-1]:
                 lowerCamelCase					:					str        =	True
                 self.check_hidden_states_output(__a     ,		__a     ,		__a     ,		(padded_height, padded_width)	)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 lowerCamelCase					:					Union[str, Any]        =	True
                 self.check_hidden_states_output(__a     ,		__a     ,		__a     ,		(padded_height, padded_width)	)

     @slow
     def 		a__						(	self:						Optional[int]	)->    List[Any]:
           for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase					:					List[str]        =	FocalNetModel.from_pretrained(__a	)
                 self.assertIsNotNone(__a	)







     def 		a__						(	self:						str	)->    Any:
           lowerCamelCase     ,			lowerCamelCase					:					Optional[Any]        =	self.model_tester.prepare_config_and_inputs_for_common()

           lowerCamelCase					:					int        =	_config_zero_init(__a	)
           for model_class in self.all_model_classes:
                 lowerCamelCase					:					int        =	model_class(config=__a	)
                 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 			A__	(						unittest.TestCase):


     """simple docstring"""

     @cached_property
     def 		a__						(	self:						Optional[int]	)->    Optional[Any]:
           # TODO update organization
           return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny"""	) if is_vision_available() else None







     @slow
     def 		a__						(	self:						int	)->    Optional[Any]:
           lowerCamelCase					:					Tuple        =	FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny"""	).to(__a	)
           lowerCamelCase					:					Any        =	self.default_image_processor

           lowerCamelCase					:					Union[str, Any]        =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
           lowerCamelCase					:					int        =	image_processor(images=__a     ,		return_tensors="""pt"""	).to(__a	)

           # forward pass
           with torch.no_grad():
                 lowerCamelCase					:					Any        =	model(**__a	)

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


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


     """simple docstring"""
     snake_case__	:					str													=(FocalNetBackbone,) if is_torch_available() else ()
     snake_case__	:					Optional[int]													=FocalNetConfig

     snake_case__	:					str													=False

     def 		a__						(	self:						Union[str, Any]	)->    Tuple:
           lowerCamelCase					:					str        =	FocalNetModelTester(self	)




