



import unittest

from transformers import LiltConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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 (
				    LiltForQuestionAnswering,
				    LiltForSequenceClassification,
				    LiltForTokenClassification,
				    LiltModel,
				)
				from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST


class       a							:



		def __init__(     self     :Tuple   ,__lowercase     :List[Any]   ,__lowercase     :str=1_3   ,__lowercase     :Optional[int]=7   ,__lowercase     :str=True   ,__lowercase     :int=True   ,__lowercase     :Dict=True   ,__lowercase     :str=True   ,__lowercase     :str=9_9   ,__lowercase     :str=2_4   ,__lowercase     :Union[str, Any]=2   ,__lowercase     :Optional[Any]=6   ,__lowercase     :Optional[int]=3_7   ,__lowercase     :List[Any]="gelu"   ,__lowercase     :str=0.1   ,__lowercase     :List[Any]=0.1   ,__lowercase     :List[str]=5_1_2   ,__lowercase     :List[str]=1_6   ,__lowercase     :Union[str, Any]=2   ,__lowercase     :int=0.02   ,__lowercase     :Optional[Any]=3   ,__lowercase     :Optional[int]=None   ,__lowercase     :Tuple=1_0_0_0   ,):
						snake_case__	:      Optional[Any]     		=	parent
						snake_case__	:      List[str]     		=	batch_size
						snake_case__	:      List[str]     		=	seq_length
						snake_case__	:      str     		=	is_training
						snake_case__	:      str     		=	use_input_mask
						snake_case__	:      int     		=	use_token_type_ids
						snake_case__	:      List[str]     		=	use_labels
						snake_case__	:      Optional[int]     		=	vocab_size
						snake_case__	:      Any     		=	hidden_size
						snake_case__	:      int     		=	num_hidden_layers
						snake_case__	:      List[str]     		=	num_attention_heads
						snake_case__	:      str     		=	intermediate_size
						snake_case__	:      Union[str, Any]     		=	hidden_act
						snake_case__	:      List[str]     		=	hidden_dropout_prob
						snake_case__	:      int     		=	attention_probs_dropout_prob
						snake_case__	:      int     		=	max_position_embeddings
						snake_case__	:      Tuple     		=	type_vocab_size
						snake_case__	:      Optional[Any]     		=	type_sequence_label_size
						snake_case__	:      Tuple     		=	initializer_range
						snake_case__	:      Dict     		=	num_labels
						snake_case__	:      str     		=	scope
						snake_case__	:      Optional[int]     		=	range_bbox



		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      Dict     		=	ids_tensor([self.batch_size, self.seq_length]   ,self.vocab_size  )

						snake_case__	:      Any     		=	ids_tensor([self.batch_size, self.seq_length, 4]   ,self.range_bbox  )
						# 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]:
																		snake_case__	:      int     		=	bbox[i, j, 3]
																		snake_case__	:      str     		=	bbox[i, j, 1]
																		snake_case__	:      List[str]     		=	t
														if bbox[i, j, 2] < bbox[i, j, 0]:
																		snake_case__	:      Tuple     		=	bbox[i, j, 2]
																		snake_case__	:      List[str]     		=	bbox[i, j, 0]
																		snake_case__	:      Union[str, Any]     		=	t

						snake_case__	:      List[Any]     		=	None
						if self.use_input_mask:
										snake_case__	:      Dict     		=	ids_tensor([self.batch_size, self.seq_length]   ,vocab_size=2  )

						snake_case__	:      List[Any]     		=	None
						if self.use_token_type_ids:
										snake_case__	:      Optional[Any]     		=	ids_tensor([self.batch_size, self.seq_length]   ,self.type_vocab_size  )

						snake_case__	:      int     		=	None
						snake_case__	:      Tuple     		=	None
						if self.use_labels:
										snake_case__	:      List[Any]     		=	ids_tensor([self.batch_size]   ,self.type_sequence_label_size  )
										snake_case__	:      int     		=	ids_tensor([self.batch_size, self.seq_length]   ,self.num_labels  )

						snake_case__	:      Optional[int]     		=	self.get_config()

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



		def 	__lowerCamelCase			(     self     :Dict  ):
						return LiltConfig(
						    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   ,)



		def 	__lowerCamelCase			(     self     :Optional[int]   ,__lowercase     :Dict   ,__lowercase     :Any   ,__lowercase     :Any   ,__lowercase     :Optional[int]   ,__lowercase     :int   ,__lowercase     :Union[str, Any]   ,__lowercase     :Optional[Any]   ,):
						snake_case__	:      Any     		=	LiltModel(config=SCREAMING_SNAKE_CASE__  )
						model.to(SCREAMING_SNAKE_CASE__  )
						model.eval()
						snake_case__	:      Any     		=	model(SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__   ,attention_mask=SCREAMING_SNAKE_CASE__   ,token_type_ids=SCREAMING_SNAKE_CASE__  )
						snake_case__	:      Optional[int]     		=	model(SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__   ,token_type_ids=SCREAMING_SNAKE_CASE__  )
						snake_case__	:      List[Any]     		=	model(SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__  )

						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 	__lowerCamelCase			(     self     :Tuple   ,__lowercase     :str   ,__lowercase     :int   ,__lowercase     :int   ,__lowercase     :Union[str, Any]   ,__lowercase     :Optional[int]   ,__lowercase     :Any   ,__lowercase     :Optional[Any]   ,):
						snake_case__	:      Any     		=	self.num_labels
						snake_case__	:      str     		=	LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__  )
						model.to(SCREAMING_SNAKE_CASE__  )
						model.eval()
						snake_case__	:      str     		=	model(
						    SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__   ,attention_mask=SCREAMING_SNAKE_CASE__   ,token_type_ids=SCREAMING_SNAKE_CASE__   ,labels=SCREAMING_SNAKE_CASE__  )
						self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.seq_length, self.num_labels)  )



		def 	__lowerCamelCase			(     self     :Any   ,__lowercase     :Tuple   ,__lowercase     :List[str]   ,__lowercase     :List[str]   ,__lowercase     :int   ,__lowercase     :Any   ,__lowercase     :Dict   ,__lowercase     :Union[str, Any]   ,):
						snake_case__	:      Union[str, Any]     		=	LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__  )
						model.to(SCREAMING_SNAKE_CASE__  )
						model.eval()
						snake_case__	:      List[str]     		=	model(
						    SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__   ,attention_mask=SCREAMING_SNAKE_CASE__   ,token_type_ids=SCREAMING_SNAKE_CASE__   ,start_positions=SCREAMING_SNAKE_CASE__   ,end_positions=SCREAMING_SNAKE_CASE__   ,)
						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 	__lowerCamelCase			(     self     :int  ):
						snake_case__	:      int     		=	self.prepare_config_and_inputs()
						(
						    snake_case__		
						)	:      List[Any]     		=	config_and_inputs
						snake_case__	:      Optional[int]     		=	{
						    'input_ids': input_ids,
						    'bbox': bbox,
						    'token_type_ids': token_type_ids,
						    'attention_mask': input_mask,
						}
						return config, inputs_dict


@require_torch
class       a							(			lowercase__  ,							lowercase__  ,							lowercase__  ,							unittest.TestCase				):
		__lowerCAmelCase	:    Union[str, Any]											=					(
		    (
		        LiltModel,
		        LiltForSequenceClassification,
		        LiltForTokenClassification,
		        LiltForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		__lowerCAmelCase	:    str											=					(
		    {
		        '''feature-extraction''': LiltModel,
		        '''question-answering''': LiltForQuestionAnswering,
		        '''text-classification''': LiltForSequenceClassification,
		        '''token-classification''': LiltForTokenClassification,
		        '''zero-shot''': LiltForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		__lowerCAmelCase	:    List[str]											=					False
		__lowerCAmelCase	:    str											=					False



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :str   ,__lowercase     :Tuple   ,__lowercase     :List[str]   ,__lowercase     :Optional[int]   ,__lowercase     :int  ):
						return True



		def 	__lowerCamelCase			(     self     :Optional[Any]  ):
						snake_case__	:      str     		=	LiltModelTester(self  )
						snake_case__	:      List[Any]     		=	ConfigTester(self   ,config_class=SCREAMING_SNAKE_CASE__   ,hidden_size=3_7  )



		def 	__lowerCamelCase			(     self     :Dict  ):
						self.config_tester.run_common_tests()



		def 	__lowerCamelCase			(     self     :Optional[int]  ):
						snake_case__	:      Dict     		=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__  )



		def 	__lowerCamelCase			(     self     :Dict  ):
						snake_case__	:      Tuple     		=	self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
										snake_case__	:      List[str]     		=	type
										self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__  )



		def 	__lowerCamelCase			(     self     :int  ):
						snake_case__	:      List[Any]     		=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__  )



		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      Optional[Any]     		=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__  )






		@slow
		def 	__lowerCamelCase			(     self     :str  ):
						for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										snake_case__	:      List[Any]     		=	LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__  )
										self.assertIsNotNone(SCREAMING_SNAKE_CASE__  )


@require_torch
@slow
class       a							(			unittest.TestCase				):



		def 	__lowerCamelCase			(     self     :Union[str, Any]  ):
						snake_case__	:      List[str]     		=	LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base'''  ).to(SCREAMING_SNAKE_CASE__  )

						snake_case__	:      str     		=	torch.tensor([[1, 2]]   ,device=SCREAMING_SNAKE_CASE__  )
						snake_case__	:      List[Any]     		=	torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]   ,device=SCREAMING_SNAKE_CASE__  )

						# forward pass
						with torch.no_grad():
										snake_case__	:      str     		=	model(input_ids=SCREAMING_SNAKE_CASE__   ,bbox=SCREAMING_SNAKE_CASE__  )

						snake_case__	:      Optional[int]     		=	torch.Size([1, 2, 7_6_8]  )
						snake_case__	:      int     		=	torch.tensor(
						    [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]]   ,device=SCREAMING_SNAKE_CASE__   ,)

						self.assertTrue(outputs.last_hidden_state.shape   ,SCREAMING_SNAKE_CASE__  )
						self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3]   ,SCREAMING_SNAKE_CASE__   ,atol=1e-3  )  )





import copy
from typing import Dict, List, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


UpperCAmelCase_      : Optional[int]  					=       {
    'facebook/mask2former-swin-small-coco-instance': (
        'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json'
    )
    # See all Mask2Former models at https://huggingface.co/models?filter=mask2former
}

UpperCAmelCase_      : List[str]  					=       logging.get_logger(__name__)
class  SCREAMING_SNAKE_CASE__  (				lowercase__			):
      snake_case__				:     Any        =						'''mask2former'''
      snake_case__				:     Any        =						['''swin''']
      snake_case__				:     str        =						{'''hidden_size''': '''hidden_dim'''}
      def __init__(       self				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[Dict] = None     ,							SCREAMING_SNAKE_CASE__				:       int = 2_5_6     ,							SCREAMING_SNAKE_CASE__				:       int = 2_5_6     ,							SCREAMING_SNAKE_CASE__				:       int = 2_5_6     ,							SCREAMING_SNAKE_CASE__				:       int = 1_0_2_4     ,							SCREAMING_SNAKE_CASE__				:       str = "relu"     ,							SCREAMING_SNAKE_CASE__				:       int = 6     ,							SCREAMING_SNAKE_CASE__				:       int = 1_0     ,							SCREAMING_SNAKE_CASE__				:       int = 8     ,							SCREAMING_SNAKE_CASE__				:       float = 0.0     ,							SCREAMING_SNAKE_CASE__				:       int = 2_0_4_8     ,							SCREAMING_SNAKE_CASE__				:       bool = False     ,							SCREAMING_SNAKE_CASE__				:       bool = False     ,							SCREAMING_SNAKE_CASE__				:       int = 4     ,							SCREAMING_SNAKE_CASE__				:       int = 2_5_5     ,							SCREAMING_SNAKE_CASE__				:       int = 1_0_0     ,							SCREAMING_SNAKE_CASE__				:       float = 0.1     ,							SCREAMING_SNAKE_CASE__				:       float = 2.0     ,							SCREAMING_SNAKE_CASE__				:       float = 5.0     ,							SCREAMING_SNAKE_CASE__				:       float = 5.0     ,							SCREAMING_SNAKE_CASE__				:       int = 1_2_5_4_4     ,							SCREAMING_SNAKE_CASE__				:       float = 3.0     ,							SCREAMING_SNAKE_CASE__				:       float = 0.75     ,							SCREAMING_SNAKE_CASE__				:       float = 0.02     ,							SCREAMING_SNAKE_CASE__				:       float = 1.0     ,							SCREAMING_SNAKE_CASE__				:       bool = True     ,							SCREAMING_SNAKE_CASE__				:       List[int] = [4, 8, 1_6, 3_2]     ,							SCREAMING_SNAKE_CASE__				:       bool = None     ,							**SCREAMING_SNAKE_CASE__				:       int     ,							)		->			List[Any]:
             if backbone_config is None:
                    logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.'     )
                    a_					:		Dict							=  CONFIG_MAPPING['swin'](
                        image_size=2_2_4     ,							in_channels=3     ,							patch_size=4     ,							embed_dim=9_6     ,							depths=[2, 2, 1_8, 2]     ,							num_heads=[3, 6, 1_2, 2_4]     ,							window_size=7     ,							drop_path_rate=0.3     ,							use_absolute_embeddings=SCREAMING_SNAKE_CASE__     ,							out_features=['stage1', 'stage2', 'stage3', 'stage4']     ,							)

             if isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ):
                    a_					:		Any							=  backbone_config.pop('model_type'     )
                    a_					:		Optional[Any]							=  CONFIG_MAPPING[backbone_model_type]
                    a_					:		List[str]							=  config_class.from_dict(SCREAMING_SNAKE_CASE__     )

             # verify that the backbone is supported
             if backbone_config.model_type not in self.backbones_supported:
                    logger.warning_once(
                        F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """
                        F"""Supported model types: {",".join(self.backbones_supported     )}"""     )

             a_					:		Dict							=  backbone_config
             a_					:		List[str]							=  feature_size
             a_					:		List[str]							=  mask_feature_size
             a_					:		int							=  hidden_dim
             a_					:		Dict							=  encoder_feedforward_dim
             a_					:		str							=  activation_function
             a_					:		List[str]							=  encoder_layers
             a_					:		List[str]							=  decoder_layers
             a_					:		Dict							=  num_attention_heads
             a_					:		str							=  dropout
             a_					:		Tuple							=  dim_feedforward
             a_					:		List[str]							=  pre_norm
             a_					:		Optional[int]							=  enforce_input_projection
             a_					:		Any							=  common_stride
             a_					:		Optional[int]							=  ignore_value
             a_					:		int							=  num_queries
             a_					:		Tuple							=  no_object_weight
             a_					:		Dict							=  class_weight
             a_					:		Optional[int]							=  mask_weight
             a_					:		Optional[int]							=  dice_weight
             a_					:		str							=  train_num_points
             a_					:		List[str]							=  oversample_ratio
             a_					:		List[Any]							=  importance_sample_ratio
             a_					:		Any							=  init_std
             a_					:		Union[str, Any]							=  init_xavier_std
             a_					:		Union[str, Any]							=  use_auxiliary_loss
             a_					:		Dict							=  feature_strides
             a_					:		List[str]							=  output_auxiliary_logits
             a_					:		Dict							=  decoder_layers

             super().__init__(**SCREAMING_SNAKE_CASE__     )
      @classmethod
      def        SCREAMING_SNAKE_CASE							(       cls				:       str     ,							SCREAMING_SNAKE_CASE__				:       PretrainedConfig     ,							**SCREAMING_SNAKE_CASE__				:       Union[str, Any]     )		->			List[Any]:
             return cls(
                 backbone_config=SCREAMING_SNAKE_CASE__     ,							**SCREAMING_SNAKE_CASE__     ,							)

      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			Dict[str, any]:
             a_					:		Optional[int]							=  copy.deepcopy(self.__dict__     )
             a_					:		List[Any]							=  self.backbone_config.to_dict()
             a_					:		Optional[Any]							=  self.__class__.model_type
             return output


