

'''simple docstring'''
from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings







@maybe_allow_in_graph
class 							A__    (       nn.Module  ):





  def __init__(		self      :	List[Any]							,					_a      :	int							,					_a      :	int							,					_a      :	int							,					_a      :	int=0.0							,					_a      :	Optional[int] = None							,					_a      :	str = "geglu"							,					_a      :	Optional[int] = None							,					_a      :	bool = False							,					_a      :	bool = False							,					_a      :	bool = False							,					_a      :	bool = False							,					_a      :	bool = True							,					_a      :	str = "layer_norm"							,					_a      :	bool = False							,					)	->    List[str]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =only_cross_attention

       _SCREAMING_SNAKE_CASE							    =(num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero'
       _SCREAMING_SNAKE_CASE							    =(num_embeds_ada_norm is not None) and norm_type == 'ada_norm'

       if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
            raise ValueError(
                f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
                f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." )

       # Define 3 blocks. Each block has its own normalization layer.
       # 1. Self-Attn
       if self.use_ada_layer_norm:
            _SCREAMING_SNAKE_CASE							    =AdaLayerNorm(_a							,					_a )
       elif self.use_ada_layer_norm_zero:
            _SCREAMING_SNAKE_CASE							    =AdaLayerNormZero(_a							,					_a )
       else:
            _SCREAMING_SNAKE_CASE							    =nn.LayerNorm(_a							,					elementwise_affine=_a )
       _SCREAMING_SNAKE_CASE							    =Attention(
           query_dim=_a							,					heads=_a							,					dim_head=_a							,					dropout=_a							,					bias=_a							,					cross_attention_dim=cross_attention_dim if only_cross_attention else None							,					upcast_attention=_a							,					)

       # 2. Cross-Attn
       if cross_attention_dim is not None or double_self_attention:
            # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
            # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
            # the second cross attention block.
            _SCREAMING_SNAKE_CASE							    =(
                AdaLayerNorm(_a							,					_a )
                if self.use_ada_layer_norm
                else nn.LayerNorm(_a							,					elementwise_affine=_a )
            )
            _SCREAMING_SNAKE_CASE							    =Attention(
                query_dim=_a							,					cross_attention_dim=cross_attention_dim if not double_self_attention else None							,					heads=_a							,					dim_head=_a							,					dropout=_a							,					bias=_a							,					upcast_attention=_a							,					)  # is self-attn if encoder_hidden_states is none
       else:
            _SCREAMING_SNAKE_CASE							    =None
            _SCREAMING_SNAKE_CASE							    =None

       # 3. Feed-forward
       _SCREAMING_SNAKE_CASE							    =nn.LayerNorm(_a							,					elementwise_affine=_a )
       _SCREAMING_SNAKE_CASE							    =FeedForward(_a							,					dropout=_a							,					activation_fn=_a							,					final_dropout=_a )

       # let chunk size default to None
       _SCREAMING_SNAKE_CASE							    =None
       _SCREAMING_SNAKE_CASE							    =0





  def 						A  (		self      :	Tuple							,					_a      :	Optional[int]							,					_a      :	int )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =chunk_size
       _SCREAMING_SNAKE_CASE							    =dim





  def 						A  (		self      :	List[Any]							,					_a      :	torch.FloatTensor							,					_a      :	Optional[torch.FloatTensor] = None							,					_a      :	Optional[torch.FloatTensor] = None							,					_a      :	Optional[torch.FloatTensor] = None							,					_a      :	Optional[torch.LongTensor] = None							,					_a      :	Dict[str, Any] = None							,					_a      :	Optional[torch.LongTensor] = None							,					)	->    Tuple:





       '''simple docstring'''






       if self.use_ada_layer_norm:
            _SCREAMING_SNAKE_CASE							    =self.norma(_a							,					_a )
       elif self.use_ada_layer_norm_zero:
            _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.norma(
                _a							,					_a							,					_a							,					hidden_dtype=hidden_states.dtype )
       else:
            _SCREAMING_SNAKE_CASE							    =self.norma(_a )

       _SCREAMING_SNAKE_CASE							    =cross_attention_kwargs if cross_attention_kwargs is not None else {}

       _SCREAMING_SNAKE_CASE							    =self.attna(
           _a							,					encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None							,					attention_mask=_a							,					**_a							,					)
       if self.use_ada_layer_norm_zero:
            _SCREAMING_SNAKE_CASE							    =gate_msa.unsqueeze(1 ) * attn_output
       _SCREAMING_SNAKE_CASE							    =attn_output + hidden_states

       # 2. Cross-Attention
       if self.attna is not None:
            _SCREAMING_SNAKE_CASE							    =(
                self.norma(_a							,					_a ) if self.use_ada_layer_norm else self.norma(_a )
            )

            _SCREAMING_SNAKE_CASE							    =self.attna(
                _a							,					encoder_hidden_states=_a							,					attention_mask=_a							,					**_a							,					)
            _SCREAMING_SNAKE_CASE							    =attn_output + hidden_states

       # 3. Feed-forward
       _SCREAMING_SNAKE_CASE							    =self.norma(_a )

       if self.use_ada_layer_norm_zero:
            _SCREAMING_SNAKE_CASE							    =norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

       if self._chunk_size is not None:
            # "feed_forward_chunk_size" can be used to save memory
            if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
                 raise ValueError(
                     f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." )

            _SCREAMING_SNAKE_CASE							    =norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
            _SCREAMING_SNAKE_CASE							    =torch.cat(
                [self.ff(_a ) for hid_slice in norm_hidden_states.chunk(_a							,					dim=self._chunk_dim )]							,					dim=self._chunk_dim							,					)
       else:
            _SCREAMING_SNAKE_CASE							    =self.ff(_a )

       if self.use_ada_layer_norm_zero:
            _SCREAMING_SNAKE_CASE							    =gate_mlp.unsqueeze(1 ) * ff_output

       _SCREAMING_SNAKE_CASE							    =ff_output + hidden_states

       return hidden_states







class 							A__    (       nn.Module  ):





  def __init__(		self      :	List[str]							,					_a      :	int							,					_a      :	Optional[int] = None							,					_a      :	int = 4							,					_a      :	float = 0.0							,					_a      :	str = "geglu"							,					_a      :	bool = False							,					)	->    List[str]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =int(dim * mult )
       _SCREAMING_SNAKE_CASE							    =dim_out if dim_out is not None else dim

       if activation_fn == "gelu":
            _SCREAMING_SNAKE_CASE							    =GELU(_a							,					_a )
       if activation_fn == "gelu-approximate":
            _SCREAMING_SNAKE_CASE							    =GELU(_a							,					_a							,					approximate='tanh' )
       elif activation_fn == "geglu":
            _SCREAMING_SNAKE_CASE							    =GEGLU(_a							,					_a )
       elif activation_fn == "geglu-approximate":
            _SCREAMING_SNAKE_CASE							    =ApproximateGELU(_a							,					_a )

       _SCREAMING_SNAKE_CASE							    =nn.ModuleList([] )
       # project in
       self.net.append(_a )
       # project dropout
       self.net.append(nn.Dropout(_a ) )
       # project out
       self.net.append(nn.Linear(_a							,					_a ) )
       # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
       if final_dropout:
            self.net.append(nn.Dropout(_a ) )





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





       '''simple docstring'''






       for module in self.net:
            _SCREAMING_SNAKE_CASE							    =module(_a )
       return hidden_states







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Any							,					_a      :	int							,					_a      :	int							,					_a      :	str = "none" )	->    List[str]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					_a )
       _SCREAMING_SNAKE_CASE							    =approximate





  def 						A  (		self      :	List[str]							,					_a      :	int )	->    Tuple:





       '''simple docstring'''






       if gate.device.type != "mps":
            return F.gelu(_a							,					approximate=self.approximate )
       # mps: gelu is not implemented for float16
       return F.gelu(gate.to(dtype=torch.floataa )							,					approximate=self.approximate ).to(dtype=gate.dtype )





  def 						A  (		self      :	int							,					_a      :	List[str] )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.proj(_a )
       _SCREAMING_SNAKE_CASE							    =self.gelu(_a )
       return hidden_states







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Tuple							,					_a      :	int							,					_a      :	int )	->    int:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					dim_out * 2 )





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





       '''simple docstring'''






       if gate.device.type != "mps":
            return F.gelu(_a )
       # mps: gelu is not implemented for float16
       return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype )





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.proj(_a ).chunk(2							,					dim=-1 )
       return hidden_states * self.gelu(_a )







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Any							,					_a      :	int							,					_a      :	int )	->    List[Any]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					_a )





  def 						A  (		self      :	str							,					_a      :	List[str] )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.proj(_a )
       return x * torch.sigmoid(1.7_02 * x )







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Dict							,					_a      :	int							,					_a      :	Tuple )	->    List[Any]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =nn.Embedding(_a							,					_a )
       _SCREAMING_SNAKE_CASE							    =nn.SiLU()
       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					embedding_dim * 2 )
       _SCREAMING_SNAKE_CASE							    =nn.LayerNorm(_a							,					elementwise_affine=_a )





  def 						A  (		self      :	int							,					_a      :	Any							,					_a      :	Any )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.linear(self.silu(self.emb(_a ) ) )
       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =torch.chunk(_a							,					2 )
       _SCREAMING_SNAKE_CASE							    =self.norm(_a ) * (1 + scale) + shift
       return x







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Tuple							,					_a      :	Tuple							,					_a      :	Dict )	->    Optional[int]:





       '''simple docstring'''






       super().__init__()

       _SCREAMING_SNAKE_CASE							    =CombinedTimestepLabelEmbeddings(_a							,					_a )

       _SCREAMING_SNAKE_CASE							    =nn.SiLU()
       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					6 * embedding_dim							,					bias=_a )
       _SCREAMING_SNAKE_CASE							    =nn.LayerNorm(_a							,					elementwise_affine=_a							,					eps=1e-6 )





  def 						A  (		self      :	Tuple							,					_a      :	List[str]							,					_a      :	Union[str, Any]							,					_a      :	str							,					_a      :	Optional[int]=None )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.linear(self.silu(self.emb(_a							,					_a							,					hidden_dtype=_a ) ) )
       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =emb.chunk(6							,					dim=1 )
       _SCREAMING_SNAKE_CASE							    =self.norm(_a ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
       return x, gate_msa, shift_mlp, scale_mlp, gate_mlp







class 							A__    (       nn.Module  ):





  def __init__(		self      :	Any							,					_a      :	int							,					_a      :	int							,					_a      :	int							,					_a      :	Optional[str] = None							,					_a      :	float = 1e-5 )	->    List[Any]:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							    =num_groups
       _SCREAMING_SNAKE_CASE							    =eps

       if act_fn is None:
            _SCREAMING_SNAKE_CASE							    =None
       else:
            _SCREAMING_SNAKE_CASE							    =get_activation(_a )

       _SCREAMING_SNAKE_CASE							    =nn.Linear(_a							,					out_dim * 2 )





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





       '''simple docstring'''






       if self.act:
            _SCREAMING_SNAKE_CASE							    =self.act(_a )
       _SCREAMING_SNAKE_CASE							    =self.linear(_a )
       _SCREAMING_SNAKE_CASE							    =emb[:, :, None, None]
       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =emb.chunk(2							,					dim=1 )

       _SCREAMING_SNAKE_CASE							    =F.group_norm(_a							,					self.num_groups							,					eps=self.eps )
       _SCREAMING_SNAKE_CASE							    =x * (1 + scale) + shift
       return x



'''simple docstring'''
import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

     from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
     lowerCamelCase :      int					 =     False

if is_vision_available():
     from PIL import Image

     from transformers import PixaStructImageProcessor







class 							A__    (       unittest.TestCase  ):





  def __init__(		self      :	List[str]							,					_a      :	List[Any]							,					_a      :	List[str]=7							,					_a      :	List[str]=3							,					_a      :	Tuple=18							,					_a      :	Tuple=30							,					_a      :	str=400							,					_a      :	Tuple=None							,					_a      :	Union[str, Any]=True							,					_a      :	List[str]=True							,					_a      :	Optional[int]=None							,					)	->    List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =size if size is not None else {'height': 20, 'width': 20}
       _SCREAMING_SNAKE_CASE							    =parent
       _SCREAMING_SNAKE_CASE							    =batch_size
       _SCREAMING_SNAKE_CASE							    =num_channels
       _SCREAMING_SNAKE_CASE							    =image_size
       _SCREAMING_SNAKE_CASE							    =min_resolution
       _SCREAMING_SNAKE_CASE							    =max_resolution
       _SCREAMING_SNAKE_CASE							    =size
       _SCREAMING_SNAKE_CASE							    =do_normalize
       _SCREAMING_SNAKE_CASE							    =do_convert_rgb
       _SCREAMING_SNAKE_CASE							    =[512, 1024, 2048, 4096]
       _SCREAMING_SNAKE_CASE							    =patch_size if patch_size is not None else {'height': 16, 'width': 16}





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





       '''simple docstring'''






       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}





  def 						A  (		self      :	int )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       _SCREAMING_SNAKE_CASE							    =Image.open(requests.get(_a							,					stream=_a ).raw ).convert('RGB' )
       return raw_image







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11     ,   reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'     ,   )
@require_torch
@require_vision
class 							A__    (       A__     ,   unittest.TestCase  ):
  A__		 =				PixaStructImageProcessor if is_vision_available() else None





  def 						A  (		self      :	Dict )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =PixaStructImageProcessingTester(self )





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





       '''simple docstring'''






       return self.image_processor_tester.prepare_image_processor_dict()





  def 						A  (		self      :	Any )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(_a							,					'do_normalize' ) )
       self.assertTrue(hasattr(_a							,					'do_convert_rgb' ) )





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processor_tester.prepare_dummy_image()

       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       _SCREAMING_SNAKE_CASE							    =2048

       _SCREAMING_SNAKE_CASE							    =image_processor(_a							,					return_tensors='pt'							,					max_patches=_a )
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean()							,					torch.tensor(0.06_06 )							,					atol=1e-3							,					rtol=1e-3 ) )





  def 						A  (		self      :	Any )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       _SCREAMING_SNAKE_CASE							    =True

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            with self.assertRaises(_a ):
                 _SCREAMING_SNAKE_CASE							    =image_processor(
                     image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches

            _SCREAMING_SNAKE_CASE							    ='Hello'

            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a							,					header_text=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a							,					header_text=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random numpy tensors
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a							,					numpify=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					np.ndarray )

       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PyTorch tensors
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a							,					torchify=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					torch.Tensor )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11     ,   reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'     ,   )
@require_torch
@require_vision
class 							A__    (       A__     ,   unittest.TestCase  ):
  A__		 =				PixaStructImageProcessor if is_vision_available() else None





  def 						A  (		self      :	str )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =PixaStructImageProcessingTester(self							,					num_channels=4 )
       _SCREAMING_SNAKE_CASE							    =3





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





       '''simple docstring'''






       return self.image_processor_tester.prepare_image_processor_dict()





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(_a							,					'do_normalize' ) )
       self.assertTrue(hasattr(_a							,					'do_convert_rgb' ) )





  def 						A  (		self      :	Dict )	->    int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * (self.image_processor_tester.num_channels - 1)
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)
