





import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
     import onnxruntime as ort

class      A       (	__lowercase		,      unittest.TestCase						):
      _snake_case							     ='''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''



      def 	lowerCAmelCase__    (	self:						List[str]		,  _lowerCAmelCase:						str=0       )						->    str:
         '''simple docstring'''

         UpperCAmelCase_											=np.random.RandomState(_lowerCAmelCase       )
         UpperCAmelCase_											={
             "prompt": "A painting of a squirrel eating a burger",
             "generator": generator,
             "num_inference_steps": 2,
             "guidance_scale": 7.5,
             "output_type": "numpy",
         }
         return inputs



      def 	lowerCAmelCase__    (	self:						Dict       )						->    int:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.6_50_72, 0.5_84_92, 0.4_82_19, 0.5_55_21, 0.5_31_80, 0.5_59_39, 0.5_06_97, 0.3_98_00, 0.4_64_55]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						List[str]       )						->    Any:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         UpperCAmelCase_											=PNDMScheduler.from_config(pipe.scheduler.config		,  skip_prk_steps=_lowerCAmelCase       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.6_58_63, 0.5_94_25, 0.4_93_26, 0.5_63_13, 0.5_38_75, 0.5_66_27, 0.5_10_65, 0.3_97_77, 0.4_63_30]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						Dict       )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         UpperCAmelCase_											=LMSDiscreteScheduler.from_config(pipe.scheduler.config       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    List[str]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         UpperCAmelCase_											=EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						Any       )						->    Any:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         UpperCAmelCase_											=EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.5_38_17, 0.6_08_12, 0.4_73_84, 0.4_95_30, 0.5_18_94, 0.4_98_14, 0.4_79_84, 0.3_89_58, 0.4_42_71]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						List[Any]       )						->    List[str]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         UpperCAmelCase_											=DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       ).images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase_											=np.array([0.5_38_95, 0.6_08_08, 0.4_79_33, 0.4_96_08, 0.5_18_86, 0.4_99_50, 0.4_80_53, 0.3_89_57, 0.4_42_00]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



      def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    List[str]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=3 * [inputs["prompt"]]

         # forward
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       )
         UpperCAmelCase_											=output.images[0, -3:, -3:, -1]

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=3 * [inputs.pop("prompt"       )]

         UpperCAmelCase_											=pipe.tokenizer(
             _lowerCAmelCase		,  padding="max_length"		,  max_length=pipe.tokenizer.model_max_length		,  truncation=_lowerCAmelCase		,  return_tensors="np"		,  )
         UpperCAmelCase_											=text_inputs["input_ids"]

         UpperCAmelCase_											=pipe.text_encoder(input_ids=text_inputs.astype(np.intaa       )       )[0]

         UpperCAmelCase_											=prompt_embeds

         # forward
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       )
         UpperCAmelCase_											=output.images[0, -3:, -3:, -1]

         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1e-4






      def 	lowerCAmelCase__    (	self:						int       )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint		,  provider="CPUExecutionProvider"       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=3 * ["this is a negative prompt"]
         UpperCAmelCase_											=negative_prompt
         UpperCAmelCase_											=3 * [inputs["prompt"]]

         # forward
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       )
         UpperCAmelCase_											=output.images[0, -3:, -3:, -1]

         UpperCAmelCase_											=self.get_dummy_inputs()
         UpperCAmelCase_											=3 * [inputs.pop("prompt"       )]

         UpperCAmelCase_											=[]
         for p in [prompt, negative_prompt]:
            UpperCAmelCase_											=pipe.tokenizer(
                _lowerCAmelCase		,  padding="max_length"		,  max_length=pipe.tokenizer.model_max_length		,  truncation=_lowerCAmelCase		,  return_tensors="np"		,  )
            UpperCAmelCase_											=text_inputs["input_ids"]

            embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa       )       )[0]       )

         UpperCAmelCase_						,       UpperCAmelCase_											=embeds

         # forward
         UpperCAmelCase_											=pipe(**_lowerCAmelCase       )
         UpperCAmelCase_											=output.images[0, -3:, -3:, -1]

         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1e-4

@nightly
@require_onnxruntime
@require_torch_gpu
class      A       (	unittest.TestCase						):



      @property
      def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    List[Any]:
         '''simple docstring'''

         return (
             "CUDAExecutionProvider",
             {
                 "gpu_mem_limit": "15000000000",  # 15GB
                 "arena_extend_strategy": "kSameAsRequested",
             },
         )



      @property
      def 	lowerCAmelCase__    (	self:						Tuple       )						->    Tuple:
         '''simple docstring'''

         UpperCAmelCase_											=ort.SessionOptions()
         UpperCAmelCase_											=False
         return options



      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    Union[str, Any]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(
             "CompVis/stable-diffusion-v1-4"		,  revision="onnx"		,  safety_checker=_lowerCAmelCase		,  feature_extractor=_lowerCAmelCase		,  provider=self.gpu_provider		,  sess_options=self.gpu_options		,  )
         sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											="A painting of a squirrel eating a burger"
         np.random.seed(0       )
         UpperCAmelCase_											=sd_pipe([prompt]		,  guidance_scale=6.0		,  num_inference_steps=10		,  output_type="np"       )
         UpperCAmelCase_											=output.images

         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         UpperCAmelCase_											=np.array([0.04_52, 0.03_90, 0.00_87, 0.03_50, 0.06_17, 0.03_64, 0.05_44, 0.05_23, 0.07_20]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3



      def 	lowerCAmelCase__    (	self:						Tuple       )						->    Union[str, Any]:
         '''simple docstring'''

         UpperCAmelCase_											=DDIMScheduler.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  subfolder="scheduler"		,  revision="onnx"       )
         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  revision="onnx"		,  scheduler=_lowerCAmelCase		,  safety_checker=_lowerCAmelCase		,  feature_extractor=_lowerCAmelCase		,  provider=self.gpu_provider		,  sess_options=self.gpu_options		,  )
         sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											="open neural network exchange"
         UpperCAmelCase_											=np.random.RandomState(0       )
         UpperCAmelCase_											=sd_pipe([prompt]		,  guidance_scale=7.5		,  num_inference_steps=10		,  generator=_lowerCAmelCase		,  output_type="np"       )
         UpperCAmelCase_											=output.images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         UpperCAmelCase_											=np.array([0.28_67, 0.19_74, 0.14_81, 0.72_94, 0.72_51, 0.66_67, 0.41_94, 0.56_42, 0.64_86]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3



      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    Any:
         '''simple docstring'''

         UpperCAmelCase_											=LMSDiscreteScheduler.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  subfolder="scheduler"		,  revision="onnx"       )
         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  revision="onnx"		,  scheduler=_lowerCAmelCase		,  safety_checker=_lowerCAmelCase		,  feature_extractor=_lowerCAmelCase		,  provider=self.gpu_provider		,  sess_options=self.gpu_options		,  )
         sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											="open neural network exchange"
         UpperCAmelCase_											=np.random.RandomState(0       )
         UpperCAmelCase_											=sd_pipe([prompt]		,  guidance_scale=7.5		,  num_inference_steps=10		,  generator=_lowerCAmelCase		,  output_type="np"       )
         UpperCAmelCase_											=output.images
         UpperCAmelCase_											=image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         UpperCAmelCase_											=np.array([0.23_06, 0.19_59, 0.15_93, 0.65_49, 0.63_94, 0.54_08, 0.50_65, 0.60_10, 0.61_61]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3



      def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=0

         def test_callback_fn(_lowerCAmelCase:						int		,  _lowerCAmelCase:						int		,  _lowerCAmelCase:						np.ndarray       ) -> None:
            UpperCAmelCase_											=True
            nonlocal number_of_steps
            number_of_steps += 1
            if step == 0:
               assert latents.shape == (1, 4, 64, 64)
               UpperCAmelCase_											=latents[0, -3:, -3:, -1]
               UpperCAmelCase_											=np.array(
                   [-0.67_72, -0.38_35, -1.24_56, 0.19_05, -1.09_74, 0.69_67, -1.93_53, 0.01_78, 1.01_67]       )

               assert np.abs(latents_slice.flatten() - expected_slice       ).max() < 1e-3
            elif step == 5:
               assert latents.shape == (1, 4, 64, 64)
               UpperCAmelCase_											=latents[0, -3:, -3:, -1]
               UpperCAmelCase_											=np.array(
                   [-0.33_51, 0.22_41, -0.18_37, -0.23_25, -0.65_77, 0.33_93, -0.02_41, 0.58_99, 1.38_75]       )

               assert np.abs(latents_slice.flatten() - expected_slice       ).max() < 1e-3

         UpperCAmelCase_											=False

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  revision="onnx"		,  safety_checker=_lowerCAmelCase		,  feature_extractor=_lowerCAmelCase		,  provider=self.gpu_provider		,  sess_options=self.gpu_options		,  )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         UpperCAmelCase_											="Andromeda galaxy in a bottle"

         UpperCAmelCase_											=np.random.RandomState(0       )
         pipe(
             prompt=_lowerCAmelCase		,  num_inference_steps=5		,  guidance_scale=7.5		,  generator=_lowerCAmelCase		,  callback=_lowerCAmelCase		,  callback_steps=1		,  )
         assert test_callback_fn.has_been_called
         assert number_of_steps == 6






      def 	lowerCAmelCase__    (	self:						Dict       )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(
             "runwayml/stable-diffusion-v1-5"		,  revision="onnx"		,  safety_checker=_lowerCAmelCase		,  feature_extractor=_lowerCAmelCase		,  provider=self.gpu_provider		,  sess_options=self.gpu_options		,  )
         assert isinstance(_lowerCAmelCase		,  _lowerCAmelCase       )
         assert pipe.safety_checker is None

         UpperCAmelCase_											=pipe("example prompt"		,  num_inference_steps=2       ).images[0]
         assert image is not None

         # check that there's no error when saving a pipeline with one of the models being None
         with tempfile.TemporaryDirectory() as tmpdirname:
            pipe.save_pretrained(_lowerCAmelCase       )
            UpperCAmelCase_											=OnnxStableDiffusionPipeline.from_pretrained(_lowerCAmelCase       )

         # sanity check that the pipeline still works
         assert pipe.safety_checker is None
         UpperCAmelCase_											=pipe("example prompt"		,  num_inference_steps=2       ).images[0]
         assert image is not None











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:						Union[str, Any]		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						Tuple=13		,  _lowerCAmelCase:						Tuple=7		,  _lowerCAmelCase:						str=True		,  _lowerCAmelCase:						Optional[Any]=True		,  _lowerCAmelCase:						Union[str, Any]=True		,  _lowerCAmelCase:						Dict=True		,  _lowerCAmelCase:						List[Any]=99		,  _lowerCAmelCase:						str=24		,  _lowerCAmelCase:						List[str]=2		,  _lowerCAmelCase:						List[str]=6		,  _lowerCAmelCase:						Optional[int]=37		,  _lowerCAmelCase:						Dict="gelu"		,  _lowerCAmelCase:						Dict=0.1		,  _lowerCAmelCase:						List[str]=0.1		,  _lowerCAmelCase:						List[str]=512		,  _lowerCAmelCase:						List[str]=16		,  _lowerCAmelCase:						List[str]=2		,  _lowerCAmelCase:						Tuple=0.02		,  _lowerCAmelCase:						List[str]=3		,  _lowerCAmelCase:						List[str]=None		,  _lowerCAmelCase:						Optional[int]=1000		,  )						->    Tuple:
         '''simple docstring'''

         UpperCAmelCase_											=parent
         UpperCAmelCase_											=batch_size
         UpperCAmelCase_											=seq_length
         UpperCAmelCase_											=is_training
         UpperCAmelCase_											=use_input_mask
         UpperCAmelCase_											=use_token_type_ids
         UpperCAmelCase_											=use_labels
         UpperCAmelCase_											=vocab_size
         UpperCAmelCase_											=hidden_size
         UpperCAmelCase_											=num_hidden_layers
         UpperCAmelCase_											=num_attention_heads
         UpperCAmelCase_											=intermediate_size
         UpperCAmelCase_											=hidden_act
         UpperCAmelCase_											=hidden_dropout_prob
         UpperCAmelCase_											=attention_probs_dropout_prob
         UpperCAmelCase_											=max_position_embeddings
         UpperCAmelCase_											=type_vocab_size
         UpperCAmelCase_											=type_sequence_label_size
         UpperCAmelCase_											=initializer_range
         UpperCAmelCase_											=num_labels
         UpperCAmelCase_											=scope
         UpperCAmelCase_											=range_bbox



      def 	lowerCAmelCase__    (	self:						List[Any]       )						->    int:
         '''simple docstring'''

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

         UpperCAmelCase_											=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]:
                  UpperCAmelCase_											=bbox[i, j, 3]
                  UpperCAmelCase_											=bbox[i, j, 1]
                  UpperCAmelCase_											=t
               if bbox[i, j, 2] < bbox[i, j, 0]:
                  UpperCAmelCase_											=bbox[i, j, 2]
                  UpperCAmelCase_											=bbox[i, j, 0]
                  UpperCAmelCase_											=t

         UpperCAmelCase_											=None
         if self.use_input_mask:
            UpperCAmelCase_											=ids_tensor([self.batch_size, self.seq_length]		,  vocab_size=2       )

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

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

         UpperCAmelCase_											=self.get_config()

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



      def 	lowerCAmelCase__    (	self:						List[str]       )						->    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 	lowerCAmelCase__    (	self:						List[Any]		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						List[str]		,  _lowerCAmelCase:						Union[str, Any]		,  _lowerCAmelCase:						Union[str, Any]		,  _lowerCAmelCase:						List[Any]		,  _lowerCAmelCase:						Tuple		,  _lowerCAmelCase:						Optional[int]		,  )						->    Union[str, Any]:
         '''simple docstring'''

         UpperCAmelCase_											=LiltModel(config=_lowerCAmelCase       )
         model.to(_lowerCAmelCase       )
         model.eval()
         UpperCAmelCase_											=model(_lowerCAmelCase		,  bbox=_lowerCAmelCase		,  attention_mask=_lowerCAmelCase		,  token_type_ids=_lowerCAmelCase       )
         UpperCAmelCase_											=model(_lowerCAmelCase		,  bbox=_lowerCAmelCase		,  token_type_ids=_lowerCAmelCase       )
         UpperCAmelCase_											=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 	lowerCAmelCase__    (	self:						Optional[Any]		,  _lowerCAmelCase:						Union[str, Any]		,  _lowerCAmelCase:						int		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						Tuple		,  _lowerCAmelCase:						List[str]		,  _lowerCAmelCase:						Optional[Any]		,  _lowerCAmelCase:						Tuple		,  )						->    Tuple:
         '''simple docstring'''

         UpperCAmelCase_											=self.num_labels
         UpperCAmelCase_											=LiltForTokenClassification(config=_lowerCAmelCase       )
         model.to(_lowerCAmelCase       )
         model.eval()
         UpperCAmelCase_											=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 	lowerCAmelCase__    (	self:						List[Any]		,  _lowerCAmelCase:						Optional[Any]		,  _lowerCAmelCase:						List[str]		,  _lowerCAmelCase:						List[str]		,  _lowerCAmelCase:						List[str]		,  _lowerCAmelCase:						Tuple		,  _lowerCAmelCase:						int		,  _lowerCAmelCase:						Union[str, Any]		,  )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=LiltForQuestionAnswering(config=_lowerCAmelCase       )
         model.to(_lowerCAmelCase       )
         model.eval()
         UpperCAmelCase_											=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 	lowerCAmelCase__    (	self:						List[Any]       )						->    Optional[int]:
         '''simple docstring'''

         UpperCAmelCase_											=self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       (
             UpperCAmelCase_
         )						,       
         )											=config_and_inputs
         UpperCAmelCase_											={
             "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						):
      _snake_case							     =(
          (
              LiltModel,
              LiltForSequenceClassification,
              LiltForTokenClassification,
              LiltForQuestionAnswering,
          )
          if is_torch_available()
          else ()
      )
      _snake_case							     =(
          {
              '''feature-extraction''': LiltModel,
              '''question-answering''': LiltForQuestionAnswering,
              '''text-classification''': LiltForSequenceClassification,
              '''token-classification''': LiltForTokenClassification,
              '''zero-shot''': LiltForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      _snake_case							     =False
      _snake_case							     =False



      def 	lowerCAmelCase__    (	self:						Any		,  _lowerCAmelCase:						Any		,  _lowerCAmelCase:						Dict		,  _lowerCAmelCase:						List[Any]		,  _lowerCAmelCase:						Tuple		,  _lowerCAmelCase:						Optional[Any]       )						->    Tuple:
         '''simple docstring'''

         return True



      def 	lowerCAmelCase__    (	self:						Any       )						->    List[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=LiltModelTester(self       )
         UpperCAmelCase_											=ConfigTester(self		,  config_class=_lowerCAmelCase		,  hidden_size=37       )



      def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    List[Any]:
         '''simple docstring'''

         self.config_tester.run_common_tests()



      def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    str:
         '''simple docstring'''

         UpperCAmelCase_											=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase       )



      def 	lowerCAmelCase__    (	self:						List[Any]       )						->    int:
         '''simple docstring'''

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



      def 	lowerCAmelCase__    (	self:						Any       )						->    Tuple:
         '''simple docstring'''

         UpperCAmelCase_											=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*_lowerCAmelCase       )



      def 	lowerCAmelCase__    (	self:						Dict       )						->    Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*_lowerCAmelCase       )






      @slow
      def 	lowerCAmelCase__    (	self:						Tuple       )						->    int:
         '''simple docstring'''

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

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



      def 	lowerCAmelCase__    (	self:						str       )						->    Optional[Any]:
         '''simple docstring'''

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

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

         # forward pass
         with torch.no_grad():
            UpperCAmelCase_											=model(input_ids=_lowerCAmelCase		,  bbox=_lowerCAmelCase       )

         UpperCAmelCase_											=torch.Size([1, 2, 768]       )
         UpperCAmelCase_											=torch.tensor(
             [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]]		,  device=_lowerCAmelCase		,  )

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




