"""simple docstring"""







import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

       if is_vision_available():
              from transformers import MaskaFormerImageProcessor

if is_vision_available():
       from PIL import Image







class        UpperCamelCase		:
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=2     ,__UpperCamelCase=True     ,__UpperCamelCase=False     ,__UpperCamelCase=10     ,__UpperCamelCase=3     ,__UpperCamelCase=32 * 8     ,__UpperCamelCase=32 * 8     ,__UpperCamelCase=4     ,__UpperCamelCase=64     ,)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				List[str]													=	parent
        lowercase_	:				str													=	batch_size
        lowercase_	:				Tuple													=	is_training
        lowercase_	:				Any													=	use_auxiliary_loss
        lowercase_	:				int													=	num_queries
        lowercase_	:				Union[str, Any]													=	num_channels
        lowercase_	:				int													=	min_size
        lowercase_	:				int													=	max_size
        lowercase_	:				List[str]													=	num_labels
        lowercase_	:				Tuple													=	hidden_dim
        lowercase_	:				str													=	hidden_dim
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				str													=	floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]			).to(
            __UpperCamelCase			)

        lowercase_	:				int													=	torch.ones([self.batch_size, self.min_size, self.max_size]     ,device=__UpperCamelCase			)

        lowercase_	:				str													=	(
            torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]     ,device=__UpperCamelCase			) > 0.5
        ).float()
        lowercase_	:				List[str]													=	(torch.rand((self.batch_size, self.num_labels)     ,device=__UpperCamelCase			) > 0.5).long()

        lowercase_	:				List[Any]													=	self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				int													=	MaskaFormerConfig(
            hidden_size=self.hidden_dim     ,)
        lowercase_	:				List[str]													=	self.num_queries
        lowercase_	:				Any													=	self.num_labels

        lowercase_	:				Optional[int]													=	[1, 1, 1, 1]
        lowercase_	:				Union[str, Any]													=	self.num_channels

        lowercase_	:				str													=	64
        lowercase_	:				Optional[int]													=	128
        lowercase_	:				Optional[int]													=	self.hidden_dim
        lowercase_	:				Any													=	self.hidden_dim
        lowercase_	:				Dict													=	self.hidden_dim
        return config
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_							,  lowercase_							,  lowercase_							,  lowercase_	:				int													=	self.prepare_config_and_inputs()
        lowercase_	:				str													=	{'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
        return config, inputs_dict
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	output.encoder_hidden_states
        lowercase_	:				Optional[Any]													=	output.pixel_decoder_hidden_states
        lowercase_	:				List[str]													=	output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(__UpperCamelCase			)     ,len(config.backbone_config.depths			)			)
        self.parent.assertTrue(len(__UpperCamelCase			)     ,len(config.backbone_config.depths			)			)
        self.parent.assertTrue(len(__UpperCamelCase			)     ,config.decoder_layers			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase=False			)	->      Dict:


        '''simple docstring'''


        with torch.no_grad():
             lowercase_	:				str													=	MaskaFormerModel(config=__UpperCamelCase			)
             model.to(__UpperCamelCase			)
             model.eval()

             lowercase_	:				Union[str, Any]													=	model(pixel_values=__UpperCamelCase     ,pixel_mask=__UpperCamelCase			)
             lowercase_	:				Union[str, Any]													=	model(__UpperCamelCase     ,output_hidden_states=__UpperCamelCase			)

        self.parent.assertEqual(
            output.transformer_decoder_last_hidden_state.shape     ,(self.batch_size, self.num_queries, self.hidden_dim)     ,)
        # let's ensure the other two hidden state exists
        self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None			)
        self.parent.assertTrue(output.encoder_last_hidden_state is not None			)

        if output_hidden_states:
             self.check_output_hidden_state(__UpperCamelCase     ,__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				Tuple													=	MaskaFormerForUniversalSegmentation(config=__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()

        def comm_check_on_output(__UpperCamelCase			):
             # let's still check that all the required stuff is there
             self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None			)
             self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None			)
             self.parent.assertTrue(result.encoder_last_hidden_state is not None			)
             # okay, now we need to check the logits shape
             # due to the encoder compression, masks have a //4 spatial size
             self.parent.assertEqual(
                 result.masks_queries_logits.shape     ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)     ,)
             # + 1 for null class
             self.parent.assertEqual(
                 result.class_queries_logits.shape     ,(self.batch_size, self.num_queries, self.num_labels + 1)			)

        with torch.no_grad():
             lowercase_	:				List[str]													=	model(pixel_values=__UpperCamelCase     ,pixel_mask=__UpperCamelCase			)
             lowercase_	:				List[str]													=	model(__UpperCamelCase			)

             comm_check_on_output(__UpperCamelCase			)

             lowercase_	:				Optional[int]													=	model(
                 pixel_values=__UpperCamelCase     ,pixel_mask=__UpperCamelCase     ,mask_labels=__UpperCamelCase     ,class_labels=__UpperCamelCase			)

        comm_check_on_output(__UpperCamelCase			)

        self.parent.assertTrue(result.loss is not None			)
        self.parent.assertEqual(result.loss.shape     ,torch.Size([1]			)			)







@require_torch
class        UpperCamelCase		(			lowercase_						,      lowercase_						,      unittest.TestCase  ):
   lowercase							=  (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
   lowercase							=  {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

   lowercase							=  False
   lowercase							=  False
   lowercase							=  False
   lowercase							=  False
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				Tuple													=	MaskaFormerModelTester(self			)
        lowercase_	:				List[Any]													=	ConfigTester(self     ,config_class=__UpperCamelCase     ,has_text_modality=__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        self.config_tester.run_common_tests()
   def 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Optional[int]													=	self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(__UpperCamelCase     ,**__UpperCamelCase     ,output_hidden_states=__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				str													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCamelCase			)
   @unittest.skip(reason='Mask2Former does not use inputs_embeds'			)
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        pass
   @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method'			)
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        pass
   @unittest.skip(reason='Mask2Former is not a generative model'			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        pass
   @unittest.skip(reason='Mask2Former does not use token embeddings'			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        pass
   @require_torch_multi_gpu
   @unittest.skip(
       reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


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


        '''simple docstring'''


        pass
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Tuple													=	self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_	:				List[str]													=	['pixel_values']
             self.assertListEqual(arg_names[:1]     ,__UpperCamelCase			)
   @slow
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
             lowercase_	:				str													=	MaskaFormerModel.from_pretrained(__UpperCamelCase			)
             self.assertIsNotNone(__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	(self.model_tester.min_size,) * 2
        lowercase_	:				Dict													=	{
            'pixel_values': torch.randn((2, 3, *size)     ,device=__UpperCamelCase			),
            'mask_labels': torch.randn((2, 10, *size)     ,device=__UpperCamelCase			),
            'class_labels': torch.zeros(2     ,10     ,device=__UpperCamelCase			).long(),
        }
        lowercase_	:				List[str]													=	self.model_tester.get_config()

        lowercase_	:				str													=	MaskaFormerForUniversalSegmentation(__UpperCamelCase			).to(__UpperCamelCase			)
        lowercase_	:				str													=	model(**__UpperCamelCase			)
        self.assertTrue(outputs.loss is not None			)
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(__UpperCamelCase     ,**__UpperCamelCase     ,output_hidden_states=__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      str:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				str													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_	:				int													=	model_class(__UpperCamelCase			).to(__UpperCamelCase			)
             lowercase_	:				int													=	model(**__UpperCamelCase     ,output_attentions=__UpperCamelCase			)
             self.assertTrue(outputs.attentions is not None			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        if not self.model_tester.is_training:
             return

        lowercase_	:				str													=	self.all_model_classes[1]
        lowercase_							,  lowercase_							,  lowercase_							,  lowercase_							,  lowercase_	:				Union[str, Any]													=	self.model_tester.prepare_config_and_inputs()

        lowercase_	:				str													=	model_class(__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.train()

        lowercase_	:				Dict													=	model(__UpperCamelCase     ,mask_labels=__UpperCamelCase     ,class_labels=__UpperCamelCase			).loss
        loss.backward()







   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				Any													=	self.all_model_classes[1]
        lowercase_							,  lowercase_							,  lowercase_							,  lowercase_							,  lowercase_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs()
        lowercase_	:				Dict													=	True
        lowercase_	:				Tuple													=	True

        lowercase_	:				Optional[int]													=	model_class(__UpperCamelCase			).to(__UpperCamelCase			)
        model.train()

        lowercase_	:				int													=	model(__UpperCamelCase     ,mask_labels=__UpperCamelCase     ,class_labels=__UpperCamelCase			)

        lowercase_	:				str													=	outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        lowercase_	:				List[Any]													=	outputs.pixel_decoder_hidden_states[0]
        pixel_decoder_hidden_states.retain_grad()

        lowercase_	:				List[str]													=	outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        lowercase_	:				Dict													=	outputs.attentions[0]
        attentions.retain_grad()

        outputs.loss.backward(retain_graph=__UpperCamelCase			)

        self.assertIsNotNone(encoder_hidden_states.grad			)
        self.assertIsNotNone(pixel_decoder_hidden_states.grad			)
        self.assertIsNotNone(transformer_decoder_hidden_states.grad			)
        self.assertIsNotNone(attentions.grad			)






__SCREAMING_SNAKE_CASE    	=1E-4



def 			lowercase__(       ):
     lowercase_	:				str													=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
     return image







@require_vision
@slow
class        UpperCamelCase		(			unittest.TestCase  ):
   @cached_property
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        return "facebook/mask2former-swin-small-coco-instance"
   @cached_property
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints			) if is_vision_available() else None
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				Dict													=	MaskaFormerModel.from_pretrained(self.model_checkpoints			).to(__UpperCamelCase			)
        lowercase_	:				Dict													=	self.default_image_processor
        lowercase_	:				Union[str, Any]													=	prepare_img()
        lowercase_	:				int													=	image_processor(__UpperCamelCase     ,return_tensors='pt'			).to(__UpperCamelCase			)
        lowercase_	:				List[str]													=	inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
        # check size
        self.assertEqual(__UpperCamelCase     ,(1, 3, 384, 384)			)

        with torch.no_grad():
             lowercase_	:				List[str]													=	model(**__UpperCamelCase			)

        lowercase_	:				Optional[Any]													=	torch.tensor(
            [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]			).to(__UpperCamelCase			)
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3]     ,__UpperCamelCase     ,atol=__UpperCamelCase			)			)

        lowercase_	:				Optional[int]													=	torch.tensor(
            [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]			).to(__UpperCamelCase			)
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]     ,__UpperCamelCase     ,atol=__UpperCamelCase			)			)

        lowercase_	:				Tuple													=	torch.tensor(
            [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]			).to(__UpperCamelCase			)
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3]     ,__UpperCamelCase     ,atol=__UpperCamelCase			)			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(__UpperCamelCase			).eval()
        lowercase_	:				Any													=	self.default_image_processor
        lowercase_	:				List[Any]													=	prepare_img()
        lowercase_	:				Union[str, Any]													=	image_processor(__UpperCamelCase     ,return_tensors='pt'			).to(__UpperCamelCase			)
        lowercase_	:				List[str]													=	inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
        # check size
        self.assertEqual(__UpperCamelCase     ,(1, 3, 384, 384)			)

        with torch.no_grad():
             lowercase_	:				Tuple													=	model(**__UpperCamelCase			)
        # masks_queries_logits
        lowercase_	:				List[str]													=	outputs.masks_queries_logits
        self.assertEqual(
            masks_queries_logits.shape     ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)			)
        lowercase_	:				List[str]													=	[
            [-8.7839, -9.0056, -8.8121],
            [-7.4104, -7.0313, -6.5401],
            [-6.6105, -6.3427, -6.4675],
        ]
        lowercase_	:				Optional[int]													=	torch.tensor(__UpperCamelCase			).to(__UpperCamelCase			)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,__UpperCamelCase     ,atol=__UpperCamelCase			)			)
        # class_queries_logits
        lowercase_	:				int													=	outputs.class_queries_logits
        self.assertEqual(class_queries_logits.shape     ,(1, model.config.num_queries, model.config.num_labels + 1)			)
        lowercase_	:				Tuple													=	torch.tensor(
            [
                [1.8324, -8.0835, -4.1922],
                [0.8450, -9.0050, -3.6053],
                [0.3045, -7.7293, -3.0275],
            ]			).to(__UpperCamelCase			)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,__UpperCamelCase     ,atol=__UpperCamelCase			)			)







   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				List[str]													=	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(__UpperCamelCase			).eval()
        lowercase_	:				str													=	self.default_image_processor

        lowercase_	:				Optional[Any]													=	image_processor(
            [np.zeros((3, 800, 1333)			), np.zeros((3, 800, 1333)			)]     ,segmentation_maps=[np.zeros((384, 384)			).astype(np.floataa			), np.zeros((384, 384)			).astype(np.floataa			)]     ,return_tensors='pt'     ,)

        lowercase_	:				int													=	inputs['pixel_values'].to(__UpperCamelCase			)
        lowercase_	:				Any													=	[el.to(__UpperCamelCase			) for el in inputs['mask_labels']]
        lowercase_	:				int													=	[el.to(__UpperCamelCase			) for el in inputs['class_labels']]

        with torch.no_grad():
             lowercase_	:				Tuple													=	model(**__UpperCamelCase			)

        self.assertTrue(outputs.loss is not None			)


"""simple docstring"""







__SCREAMING_SNAKE_CASE    	={}



def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     int     ,			__SCREAMING_SNAKE_CASE							:     int     ,			__SCREAMING_SNAKE_CASE							:     int      ):

     # if we are absent twice, or late 3 consecutive days,
     # no further prize strings are possible
     if late == 3 or absent == 2:
          return 0

     # if we have no days left, and have not failed any other rules,
     # we have a prize string
     if days == 0:
          return 1

     # No easy solution, so now we need to do the recursive calculation

     # First, check if the combination is already in the cache, and
     # if yes, return the stored value from there since we already
     # know the number of possible prize strings from this point on
     lowercase_	:				Any													=	(days, absent, late)
     if key in cache:
          return cache[key]

     # now we calculate the three possible ways that can unfold from
     # this point on, depending on our attendance today

     # 1) if we are late (but not absent), the "absent" counter stays as
     # it is, but the "late" counter increases by one
     lowercase_	:				Optional[int]													=	_calculate(days - 1     ,			__SCREAMING_SNAKE_CASE     ,			late + 1      )

     # 2) if we are absent, the "absent" counter increases by 1, and the
     # "late" counter resets to 0
     lowercase_	:				Any													=	_calculate(days - 1     ,			absent + 1     ,			0      )

     # 3) if we are on time, this resets the "late" counter and keeps the
     # absent counter
     lowercase_	:				Dict													=	_calculate(days - 1     ,			__SCREAMING_SNAKE_CASE     ,			0      )

     lowercase_	:				str													=	state_late + state_absent + state_ontime

     lowercase_	:				Tuple													=	prizestrings
     return prizestrings



def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     int = 30      ):
     return _calculate(__SCREAMING_SNAKE_CASE     ,			absent=0     ,			late=0      )


if __name__ == "__main__":
       print(solution())

