





from __future__ import annotations

import unittest

import numpy as np

from transformers import LayoutLMConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers.models.layoutlm.modeling_tf_layoutlm import (
           TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFLayoutLMForMaskedLM,
           TFLayoutLMForQuestionAnswering,
           TFLayoutLMForSequenceClassification,
           TFLayoutLMForTokenClassification,
           TFLayoutLMModel,
       )




class     SCREAMING_SNAKE_CASE__ :



 def __init__(							self,__lowerCamelCase,__lowerCamelCase=13,__lowerCamelCase=7,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=99,__lowerCamelCase=32,__lowerCamelCase=2,__lowerCamelCase=4,__lowerCamelCase=37,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=512,__lowerCamelCase=16,__lowerCamelCase=2,__lowerCamelCase=0.02,__lowerCamelCase=3,__lowerCamelCase=4,__lowerCamelCase=None,__lowerCamelCase=1000,):
        A__											=						parent
        A__											=						batch_size
        A__											=						seq_length
        A__											=						is_training
        A__											=						use_input_mask
        A__											=						use_token_type_ids
        A__											=						use_labels
        A__											=						vocab_size
        A__											=						hidden_size
        A__											=						num_hidden_layers
        A__											=						num_attention_heads
        A__											=						intermediate_size
        A__											=						hidden_act
        A__											=						hidden_dropout_prob
        A__											=						attention_probs_dropout_prob
        A__											=						max_position_embeddings
        A__											=						type_vocab_size
        A__											=						type_sequence_label_size
        A__											=						initializer_range
        A__											=						num_labels
        A__											=						num_choices
        A__											=						scope
        A__											=						range_bbox



 def 				UpperCamelCase			(							self ):
        A__											=						ids_tensor([self.batch_size, self.seq_length],self.vocab_size )

        # convert bbox to numpy since TF does not support item assignment
        A__											=						ids_tensor([self.batch_size, self.seq_length, 4],self.range_bbox ).numpy()
        # Ensure that bbox is legal
        for i in range(bbox.shape[0] ):
               for j in range(bbox.shape[1] ):
                      if bbox[i, j, 3] < bbox[i, j, 1]:
                             A__											=						bbox[i, j, 3]
                             A__											=						bbox[i, j, 1]
                             A__											=						t
                      if bbox[i, j, 2] < bbox[i, j, 0]:
                             A__											=						bbox[i, j, 2]
                             A__											=						bbox[i, j, 0]
                             A__											=						t
        A__											=						tf.convert_to_tensor(__lowerCamelCase )

        A__											=						None
        if self.use_input_mask:
               A__											=						random_attention_mask([self.batch_size, self.seq_length] )

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

        A__											=						None
        A__											=						None
        A__											=						None
        if self.use_labels:
               A__											=						ids_tensor([self.batch_size],self.type_sequence_label_size )
               A__											=						ids_tensor([self.batch_size, self.seq_length],self.num_labels )
               A__											=						ids_tensor([self.batch_size],self.num_choices )

        A__											=						LayoutLMConfig(
            vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,)

        return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						TFLayoutLMModel(config=__lowerCamelCase )

        A__											=						model(__lowerCamelCase,__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase )
        A__											=						model(__lowerCamelCase,__lowerCamelCase,token_type_ids=__lowerCamelCase )
        A__											=						model(__lowerCamelCase,__lowerCamelCase )
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size) )
        self.parent.assertEqual(result.pooler_output.shape,(self.batch_size, self.hidden_size) )



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						TFLayoutLMForMaskedLM(config=__lowerCamelCase )

        A__											=						model(__lowerCamelCase,__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase,labels=__lowerCamelCase )
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size) )



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						self.num_labels
        A__											=						TFLayoutLMForSequenceClassification(config=__lowerCamelCase )

        A__											=						model(__lowerCamelCase,__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase )
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels) )



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						self.num_labels
        A__											=						TFLayoutLMForTokenClassification(config=__lowerCamelCase )

        A__											=						model(__lowerCamelCase,__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase,labels=__lowerCamelCase )
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels) )



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						TFLayoutLMForQuestionAnswering(config=__lowerCamelCase )

        A__											=						model(__lowerCamelCase,__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase )
        self.parent.assertEqual(result.start_logits.shape,(self.batch_size, self.seq_length) )
        self.parent.assertEqual(result.end_logits.shape,(self.batch_size, self.seq_length) )




 def 				UpperCamelCase			(							self ):
        A__											=						self.prepare_config_and_inputs()
        (
            (
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	(
            A__
        )					,	
        )											=						config_and_inputs
        A__											=						{
            '''input_ids''': input_ids,
            '''bbox''': bbox,
            '''token_type_ids''': token_type_ids,
            '''attention_mask''': input_mask,
        }
        return config, inputs_dict




@require_tf
class     SCREAMING_SNAKE_CASE__ (						UpperCamelCase__				,					UpperCamelCase__				,					unittest.TestCase      ):
 __SCREAMING_SNAKE_CASE							       =	(
     (
         TFLayoutLMModel,
         TFLayoutLMForMaskedLM,
         TFLayoutLMForTokenClassification,
         TFLayoutLMForSequenceClassification,
         TFLayoutLMForQuestionAnswering,
     )
     if is_tf_available()
     else ()
 )
 __SCREAMING_SNAKE_CASE							       =	(
     {
         '''feature-extraction''': TFLayoutLMModel,
         '''fill-mask''': TFLayoutLMForMaskedLM,
         '''text-classification''': TFLayoutLMForSequenceClassification,
         '''token-classification''': TFLayoutLMForTokenClassification,
         '''zero-shot''': TFLayoutLMForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 __SCREAMING_SNAKE_CASE							       =	False
 __SCREAMING_SNAKE_CASE							       =	True
 __SCREAMING_SNAKE_CASE							       =	10



 def 				UpperCamelCase			(							self ):
        A__											=						TFLayoutLMModelTester(self )
        A__											=						ConfigTester(self,config_class=__lowerCamelCase,hidden_size=37 )



 def 				UpperCamelCase			(							self ):
        self.config_tester.run_common_tests()



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase )



 @slow
 def 				UpperCamelCase			(							self ):
        for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A__											=						TFLayoutLMModel.from_pretrained(__lowerCamelCase )
               self.assertIsNotNone(__lowerCamelCase )




 @unittest.skip('''Onnx compliancy broke with TF 2.10''' )
 def 				UpperCamelCase			(							self ):
        pass


def 	UpperCamelCase__(       )->Optional[Any]:
       # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on:
       # fmt: off
       A__											=						tf.convert_to_tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]]  )  # noqa: E231
       A__											=						tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],]  )  # noqa: E231
       A__											=						tf.convert_to_tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]]  )  # noqa: E231
       A__											=						tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]  )  # noqa: E231
       # these are sequence labels (i.e. at the token level)
       A__											=						tf.convert_to_tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]]  )  # noqa: E231
       # fmt: on

       return input_ids, attention_mask, bbox, token_type_ids, labels




@require_tf
class     SCREAMING_SNAKE_CASE__ (						unittest.TestCase      ):



 @slow
 def 				UpperCamelCase			(							self ):
        A__											=						TFLayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased''' )

        A__					,	A__					,	A__					,	A__					,	A__											=						prepare_layoutlm_batch_inputs()

        # forward pass
        A__											=						model(input_ids=__lowerCamelCase,bbox=__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase )

        # test the sequence output on [0, :3, :3]
        A__											=						tf.convert_to_tensor(
            [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]],)

        self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3],__lowerCamelCase,atol=1E-3 ) )

        # test the pooled output on [1, :3]
        A__											=						tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] )

        self.assertTrue(np.allclose(outputs.pooler_output[1, :3],__lowerCamelCase,atol=1E-3 ) )



 @slow
 def 				UpperCamelCase			(							self ):
        # initialize model with randomly initialized sequence classification head
        A__											=						TFLayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased''',num_labels=2 )

        A__					,	A__					,	A__					,	A__					,	A__											=						prepare_layoutlm_batch_inputs()

        # forward pass
        A__											=						model(
            input_ids=__lowerCamelCase,bbox=__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase,labels=tf.convert_to_tensor([1, 1] ),)

        # test whether we get a loss as a scalar
        A__											=						outputs.loss
        A__											=						(2,)
        self.assertEqual(loss.shape,__lowerCamelCase )

        # test the shape of the logits
        A__											=						outputs.logits
        A__											=						(2, 2)
        self.assertEqual(logits.shape,__lowerCamelCase )



 @slow
 def 				UpperCamelCase			(							self ):
        # initialize model with randomly initialized token classification head
        A__											=						TFLayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased''',num_labels=13 )

        A__					,	A__					,	A__					,	A__					,	A__											=						prepare_layoutlm_batch_inputs()

        # forward pass
        A__											=						model(
            input_ids=__lowerCamelCase,bbox=__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase,labels=__lowerCamelCase )

        # test the shape of the logits
        A__											=						outputs.logits
        A__											=						tf.convert_to_tensor((2, 25, 13) )
        self.assertEqual(logits.shape,__lowerCamelCase )




 @slow
 def 				UpperCamelCase			(							self ):
        # initialize model with randomly initialized token classification head
        A__											=						TFLayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased''' )

        A__					,	A__					,	A__					,	A__					,	A__											=						prepare_layoutlm_batch_inputs()

        # forward pass
        A__											=						model(input_ids=__lowerCamelCase,bbox=__lowerCamelCase,attention_mask=__lowerCamelCase,token_type_ids=__lowerCamelCase )

        # test the shape of the logits
        A__											=						tf.convert_to_tensor((2, 25) )
        self.assertEqual(outputs.start_logits.shape,__lowerCamelCase )
        self.assertEqual(outputs.end_logits.shape,__lowerCamelCase )












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     SCREAMING_SNAKE_CASE__ :



 def __init__(							self,__lowerCamelCase,__lowerCamelCase=2,__lowerCamelCase=True,__lowerCamelCase=False,__lowerCamelCase=10,__lowerCamelCase=3,__lowerCamelCase=32 * 8,__lowerCamelCase=32 * 8,__lowerCamelCase=4,__lowerCamelCase=64,):
        A__											=						parent
        A__											=						batch_size
        A__											=						is_training
        A__											=						use_auxiliary_loss
        A__											=						num_queries
        A__											=						num_channels
        A__											=						min_size
        A__											=						max_size
        A__											=						num_labels
        A__											=						hidden_dim
        A__											=						hidden_dim



 def 				UpperCamelCase			(							self ):
        A__											=						floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
            __lowerCamelCase )

        A__											=						torch.ones([self.batch_size, self.min_size, self.max_size],device=__lowerCamelCase )

        A__											=						(
            torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size],device=__lowerCamelCase ) > 0.5
        ).float()
        A__											=						(torch.rand((self.batch_size, self.num_labels),device=__lowerCamelCase ) > 0.5).long()

        A__											=						self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels



 def 				UpperCamelCase			(							self ):
        A__											=						MaskaFormerConfig(
            hidden_size=self.hidden_dim,)
        A__											=						self.num_queries
        A__											=						self.num_labels

        A__											=						[1, 1, 1, 1]
        A__											=						self.num_channels

        A__											=						64
        A__											=						128
        A__											=						self.hidden_dim
        A__											=						self.hidden_dim
        A__											=						self.hidden_dim
        return config



 def 				UpperCamelCase			(							self ):
        A__					,	A__					,	A__					,	A__					,	A__											=						self.prepare_config_and_inputs()
        A__											=						{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
        return config, inputs_dict



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase ):
        A__											=						output.encoder_hidden_states
        A__											=						output.pixel_decoder_hidden_states
        A__											=						output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(__lowerCamelCase ),len(config.backbone_config.depths ) )
        self.parent.assertTrue(len(__lowerCamelCase ),len(config.backbone_config.depths ) )
        self.parent.assertTrue(len(__lowerCamelCase ),config.decoder_layers )



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase=False ):
        with torch.no_grad():
               A__											=						MaskaFormerModel(config=__lowerCamelCase )
               model.to(__lowerCamelCase )
               model.eval()

               A__											=						model(pixel_values=__lowerCamelCase,pixel_mask=__lowerCamelCase )
               A__											=						model(__lowerCamelCase,output_hidden_states=__lowerCamelCase )

        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(__lowerCamelCase,__lowerCamelCase )




 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						MaskaFormerForUniversalSegmentation(config=__lowerCamelCase )
        model.to(__lowerCamelCase )
        model.eval()

        def comm_check_on_output(__lowerCamelCase ):
               # 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():
               A__											=						model(pixel_values=__lowerCamelCase,pixel_mask=__lowerCamelCase )
               A__											=						model(__lowerCamelCase )

               comm_check_on_output(__lowerCamelCase )

               A__											=						model(
                   pixel_values=__lowerCamelCase,pixel_mask=__lowerCamelCase,mask_labels=__lowerCamelCase,class_labels=__lowerCamelCase )

        comm_check_on_output(__lowerCamelCase )

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




@require_torch
class     SCREAMING_SNAKE_CASE__ (						UpperCamelCase__				,					UpperCamelCase__				,					unittest.TestCase      ):
 __SCREAMING_SNAKE_CASE							       =	(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
 __SCREAMING_SNAKE_CASE							       =	{'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {}

 __SCREAMING_SNAKE_CASE							       =	False
 __SCREAMING_SNAKE_CASE							       =	False
 __SCREAMING_SNAKE_CASE							       =	False
 __SCREAMING_SNAKE_CASE							       =	False



 def 				UpperCamelCase			(							self ):
        A__											=						MaskaFormerModelTester(self )
        A__											=						ConfigTester(self,config_class=__lowerCamelCase,has_text_modality=__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        self.config_tester.run_common_tests()



 def 				UpperCamelCase			(							self ):
        A__					,	A__											=						self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(__lowerCamelCase,**__lowerCamelCase,output_hidden_states=__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__lowerCamelCase )



 @unittest.skip(reason='''Mask2Former does not use inputs_embeds''' )
 def 				UpperCamelCase			(							self ):
        pass



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



 @unittest.skip(reason='''Mask2Former is not a generative model''' )
 def 				UpperCamelCase			(							self ):
        pass



 @unittest.skip(reason='''Mask2Former does not use token embeddings''' )
 def 				UpperCamelCase			(							self ):
        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 ):
        pass



 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
 def 				UpperCamelCase			(							self ):
        pass



 def 				UpperCamelCase			(							self ):
        A__					,	A__											=						self.model_tester.prepare_config_and_inputs_for_common()

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

               A__											=						['''pixel_values''']
               self.assertListEqual(arg_names[:1],__lowerCamelCase )



 @slow
 def 				UpperCamelCase			(							self ):
        for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
               A__											=						MaskaFormerModel.from_pretrained(__lowerCamelCase )
               self.assertIsNotNone(__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__											=						(self.model_tester.min_size,) * 2
        A__											=						{
            '''pixel_values''': torch.randn((2, 3, *size),device=__lowerCamelCase ),
            '''mask_labels''': torch.randn((2, 10, *size),device=__lowerCamelCase ),
            '''class_labels''': torch.zeros(2,10,device=__lowerCamelCase ).long(),
        }
        A__											=						self.model_tester.get_config()

        A__											=						MaskaFormerForUniversalSegmentation(__lowerCamelCase ).to(__lowerCamelCase )
        A__											=						model(**__lowerCamelCase )
        self.assertTrue(outputs.loss is not None )



 def 				UpperCamelCase			(							self ):
        A__					,	A__											=						self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(__lowerCamelCase,**__lowerCamelCase,output_hidden_states=__lowerCamelCase )



 def 				UpperCamelCase			(							self ):
        A__					,	A__											=						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               A__											=						model_class(__lowerCamelCase ).to(__lowerCamelCase )
               A__											=						model(**__lowerCamelCase,output_attentions=__lowerCamelCase )
               self.assertTrue(outputs.attentions is not None )



 def 				UpperCamelCase			(							self ):
        if not self.model_tester.is_training:
               return

        A__											=						self.all_model_classes[1]
        A__					,	A__					,	A__					,	A__					,	A__											=						self.model_tester.prepare_config_and_inputs()

        A__											=						model_class(__lowerCamelCase )
        model.to(__lowerCamelCase )
        model.train()

        A__											=						model(__lowerCamelCase,mask_labels=__lowerCamelCase,class_labels=__lowerCamelCase ).loss
        loss.backward()




 def 				UpperCamelCase			(							self ):
        A__											=						self.all_model_classes[1]
        A__					,	A__					,	A__					,	A__					,	A__											=						self.model_tester.prepare_config_and_inputs()
        A__											=						True
        A__											=						True

        A__											=						model_class(__lowerCamelCase ).to(__lowerCamelCase )
        model.train()

        A__											=						model(__lowerCamelCase,mask_labels=__lowerCamelCase,class_labels=__lowerCamelCase )

        A__											=						outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        A__											=						outputs.pixel_decoder_hidden_states[0]
        pixel_decoder_hidden_states.retain_grad()

        A__											=						outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        A__											=						outputs.attentions[0]
        attentions.retain_grad()

        outputs.loss.backward(retain_graph=__lowerCamelCase )

        self.assertIsNotNone(encoder_hidden_states.grad )
        self.assertIsNotNone(pixel_decoder_hidden_states.grad )
        self.assertIsNotNone(transformer_decoder_hidden_states.grad )
        self.assertIsNotNone(attentions.grad )
a__:      str									=		1e-4


def 	UpperCamelCase__(       )->Union[str, Any]:
       A__											=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
       return image




@require_vision
@slow
class     SCREAMING_SNAKE_CASE__ (						unittest.TestCase      ):



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



 @cached_property
 def 				UpperCamelCase			(							self ):
        return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None



 def 				UpperCamelCase			(							self ):
        A__											=						MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase )
        A__											=						self.default_image_processor
        A__											=						prepare_img()
        A__											=						image_processor(__lowerCamelCase,return_tensors='''pt''' ).to(__lowerCamelCase )
        A__											=						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(__lowerCamelCase,(1, 3, 384, 384) )

        with torch.no_grad():
               A__											=						model(**__lowerCamelCase )

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

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

        A__											=						torch.tensor(
            [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(__lowerCamelCase )
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3],__lowerCamelCase,atol=__lowerCamelCase ) )



 def 				UpperCamelCase			(							self ):
        A__											=						MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase ).eval()
        A__											=						self.default_image_processor
        A__											=						prepare_img()
        A__											=						image_processor(__lowerCamelCase,return_tensors='''pt''' ).to(__lowerCamelCase )
        A__											=						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(__lowerCamelCase,(1, 3, 384, 384) )

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




 def 				UpperCamelCase			(							self ):
        A__											=						MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCamelCase ).eval()
        A__											=						self.default_image_processor

        A__											=						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''',)

        A__											=						inputs['''pixel_values'''].to(__lowerCamelCase )
        A__											=						[el.to(__lowerCamelCase ) for el in inputs['''mask_labels''']]
        A__											=						[el.to(__lowerCamelCase ) for el in inputs['''class_labels''']]

        with torch.no_grad():
               A__											=						model(**__lowerCamelCase )

        self.assertTrue(outputs.loss is not None )





