



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

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]=13							,   __lowerCAmelCase			:       Optional[Any]=7							,   __lowerCAmelCase			:       Any=True							,   __lowerCAmelCase			:       List[str]=True							,   __lowerCAmelCase			:       Union[str, Any]=True							,   __lowerCAmelCase			:       Dict=True							,   __lowerCAmelCase			:       Any=99							,   __lowerCAmelCase			:       Optional[Any]=24							,   __lowerCAmelCase			:       Any=2							,   __lowerCAmelCase			:       Dict=6							,   __lowerCAmelCase			:       int=37							,   __lowerCAmelCase			:       Any="gelu"							,   __lowerCAmelCase			:       int=0.1							,   __lowerCAmelCase			:       Optional[int]=0.1							,   __lowerCAmelCase			:       Optional[Any]=512							,   __lowerCAmelCase			:       Any=16							,   __lowerCAmelCase			:       Optional[Any]=2							,   __lowerCAmelCase			:       Optional[int]=0.0_2							,   __lowerCAmelCase			:       List[str]=3							,   __lowerCAmelCase			:       Optional[Any]=None							,   __lowerCAmelCase			:       str=1000							,   )       ->				List[str]:


    """simple docstring"""






    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						=		scope
    a						=		range_bbox

   def 		A							(      self			:       Optional[Any]							)       ->				int:


    """simple docstring"""






    a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size							)

    a						=		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]:
       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						=		None
    if self.use_input_mask:
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   vocab_size=2							)

    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
    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						=		self.get_config()

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

   def 		A							(      self			:       Tuple							)       ->				List[Any]:


    """simple docstring"""






    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 		A							(      self			:       Dict							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							,   )       ->				Optional[Any]:


    """simple docstring"""






    a						=		LiltModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   bbox=__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   bbox=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   bbox=__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 		A							(      self			:       str							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   )       ->				Optional[int]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		LiltForTokenClassification(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   bbox=__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 		A							(      self			:       int							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[int]							,   )       ->				Optional[int]:


    """simple docstring"""






    a						=		LiltForQuestionAnswering(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   bbox=__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   start_positions=__lowerCAmelCase							,   end_positions=__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 		A							(      self			:       Any							)       ->				Any:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    (
        (
        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_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           LiltModel,
           LiltForSequenceClassification,
           LiltForTokenClassification,
           LiltForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {
           '''feature-extraction''': LiltModel,
           '''question-answering''': LiltForQuestionAnswering,
           '''text-classification''': LiltForSequenceClassification,
           '''token-classification''': LiltForTokenClassification,
           '''zero-shot''': LiltForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False

   def 		A							(      self			:       int							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							)       ->				int:


    """simple docstring"""






    return True

   def 		A							(      self			:       int							)       ->				int:


    """simple docstring"""






    a						=		LiltModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       str							)       ->				int:


    """simple docstring"""






    self.config_tester.run_common_tests()

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase							)

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     a						=		type
     self.model_tester.create_and_check_model(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				str:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase							)

   def 		A							(      self			:       Tuple							)       ->				List[Any]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase							)




   @slow
   def 		A							(      self			:       Union[str, Any]							)       ->				Optional[int]:


    """simple docstring"""






    for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     a						=		LiltModel.from_pretrained(__lowerCAmelCase							)
     self.assertIsNotNone(__lowerCAmelCase							)



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

   def 		A							(      self			:       int							)       ->				int:


    """simple docstring"""






    a						=		LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base"							).to(__lowerCAmelCase							)

    a						=		torch.tensor([[1, 2]]							,   device=__lowerCAmelCase							)
    a						=		torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]							,   device=__lowerCAmelCase							)

    # forward pass
    with torch.no_grad():
     a						=		model(input_ids=__lowerCAmelCase							,   bbox=__lowerCAmelCase							)

    a						=		torch.Size([1, 2, 768]							)
    a						=		torch.tensor(
        [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]]							,   device=__lowerCAmelCase							,   )

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






from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


A_		:     int        =     logging.get_logger(__name__)

A_		:     str        =     {
    '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''',
}



class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__	):
   _UpperCAmelCase     	=			'''focalnet'''

   def __init__(      self			:       int							,   __lowerCAmelCase			:       Optional[Any]=224							,   __lowerCAmelCase			:       Any=4							,   __lowerCAmelCase			:       Any=3							,   __lowerCAmelCase			:       Tuple=96							,   __lowerCAmelCase			:       Dict=False							,   __lowerCAmelCase			:       Optional[int]=[192, 384, 768, 768]							,   __lowerCAmelCase			:       Union[str, Any]=[2, 2, 6, 2]							,   __lowerCAmelCase			:       Optional[int]=[2, 2, 2, 2]							,   __lowerCAmelCase			:       Union[str, Any]=[3, 3, 3, 3]							,   __lowerCAmelCase			:       str="gelu"							,   __lowerCAmelCase			:       Any=4.0							,   __lowerCAmelCase			:       Optional[int]=0.0							,   __lowerCAmelCase			:       Tuple=0.1							,   __lowerCAmelCase			:       str=False							,   __lowerCAmelCase			:       Optional[int]=1E-4							,   __lowerCAmelCase			:       Optional[Any]=False							,   __lowerCAmelCase			:       Union[str, Any]=False							,   __lowerCAmelCase			:       str=False							,   __lowerCAmelCase			:       Any=0.0_2							,   __lowerCAmelCase			:       str=1E-5							,   __lowerCAmelCase			:       Optional[Any]=32							,   __lowerCAmelCase			:       Dict=None							,   __lowerCAmelCase			:       str=None							,   **__lowerCAmelCase			:       Any							,   )       ->				List[str]:


    """simple docstring"""






    super().__init__(**__lowerCAmelCase							)

    a						=		image_size
    a						=		patch_size
    a						=		num_channels
    a						=		embed_dim
    a						=		use_conv_embed
    a						=		hidden_sizes
    a						=		depths
    a						=		focal_levels
    a						=		focal_windows
    a						=		hidden_act
    a						=		mlp_ratio
    a						=		hidden_dropout_prob
    a						=		drop_path_rate
    a						=		use_layerscale
    a						=		layerscale_value
    a						=		use_post_layernorm
    a						=		use_post_layernorm_in_modulation
    a						=		normalize_modulator
    a						=		initializer_range
    a						=		layer_norm_eps
    a						=		encoder_stride
    a						=		["stem"] + [f"""stage{idx}""" for idx in range(1							,   len(self.depths							) + 1							)]
    a		,  a						=		get_aligned_output_features_output_indices(
        out_features=__lowerCAmelCase							,   out_indices=__lowerCAmelCase							,   stage_names=self.stage_names							)

