



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:
       lowercase_						=       False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor
class 			_snake_case     (   unittest.TestCase):




    def __init__(  self   :  List[Any],   __lowercase   :  Tuple,   __lowercase   :  Dict=7,   __lowercase   :  int=3,   __lowercase   :  List[Any]=18,   __lowercase   :  Optional[Any]=30,   __lowercase   :  List[Any]=400,   __lowercase   :  Optional[Any]=None,   __lowercase   :  Union[str, Any]=True,   __lowercase   :  List[str]=True,   __lowercase   :  Dict=None,   ):
       lowercase__   					=			size if size is not None else {"height": 20, "width": 20}
       lowercase__   					=			parent
       lowercase__   					=			batch_size
       lowercase__   					=			num_channels
       lowercase__   					=			image_size
       lowercase__   					=			min_resolution
       lowercase__   					=			max_resolution
       lowercase__   					=			size
       lowercase__   					=			do_normalize
       lowercase__   					=			do_convert_rgb
       lowercase__   					=			[512, 1024, 2048, 4096]
       lowercase__   					=			patch_size if patch_size is not None else {"height": 16, "width": 16}




    def 							A__ (  self   :  Optional[int]  ):
       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




    def 							A__ (  self   :  str  ):
       lowercase__   					=			"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
       lowercase__   					=			Image.open(requests.get(__snake_case,   stream=__snake_case  ).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 			_snake_case     (   A__      ,		unittest.TestCase):
    UpperCamelCase__			:   Any       						=PixaStructImageProcessor if is_vision_available() else None




    def 							A__ (  self   :  Tuple  ):
       lowercase__   					=			PixaStructImageProcessingTester(self  )




    @property
    def 							A__ (  self   :  List[Any]  ):
       return self.image_processor_tester.prepare_image_processor_dict()




    def 							A__ (  self   :  str  ):
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       self.assertTrue(hasattr(__snake_case,   "do_normalize"  )  )
       self.assertTrue(hasattr(__snake_case,   "do_convert_rgb"  )  )




    def 							A__ (  self   :  List[str]  ):
       lowercase__   					=			self.image_processor_tester.prepare_dummy_image()

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

       lowercase__   					=			image_processor(__snake_case,   return_tensors="pt",   max_patches=__snake_case  )
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean(),   torch.tensor(0.0606  ),   atol=1e-3,   rtol=1e-3  )  )




    def 							A__ (  self   :  str  ):
       # Initialize image_processor
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowercase__   					=			prepare_image_inputs(self.image_processor_tester,   equal_resolution=__snake_case  )
       for image in image_inputs:
          self.assertIsInstance(__snake_case,   Image.Image  )

       # Test not batched input
       lowercase__   					=			(
           (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
          lowercase__   					=			image_processor(
              image_inputs[0],   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (1, max_patch, expected_hidden_dim),   )

          # Test batched
          lowercase__   					=			image_processor(
              __snake_case,   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),   )




    def 							A__ (  self   :  str  ):
       # Initialize image_processor
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowercase__   					=			prepare_image_inputs(self.image_processor_tester,   equal_resolution=__snake_case  )
       for image in image_inputs:
          self.assertIsInstance(__snake_case,   Image.Image  )

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

       lowercase__   					=			True

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

          lowercase__   					=			"Hello"

          lowercase__   					=			image_processor(
              image_inputs[0],   return_tensors="pt",   max_patches=__snake_case,   header_text=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (1, max_patch, expected_hidden_dim),   )

          # Test batched
          lowercase__   					=			image_processor(
              __snake_case,   return_tensors="pt",   max_patches=__snake_case,   header_text=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),   )




    def 							A__ (  self   :  Union[str, Any]  ):
       # Initialize image_processor
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       # create random numpy tensors
       lowercase__   					=			prepare_image_inputs(self.image_processor_tester,   equal_resolution=__snake_case,   numpify=__snake_case  )
       for image in image_inputs:
          self.assertIsInstance(__snake_case,   np.ndarray  )

       lowercase__   					=			(
           (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
          lowercase__   					=			image_processor(
              image_inputs[0],   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (1, max_patch, expected_hidden_dim),   )

          # Test batched
          lowercase__   					=			image_processor(
              __snake_case,   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),   )




    def 							A__ (  self   :  Union[str, Any]  ):
       # Initialize image_processor
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       # create random PyTorch tensors
       lowercase__   					=			prepare_image_inputs(self.image_processor_tester,   equal_resolution=__snake_case,   torchify=__snake_case  )
       for image in image_inputs:
          self.assertIsInstance(__snake_case,   torch.Tensor  )

       # Test not batched input
       lowercase__   					=			(
           (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
          lowercase__   					=			image_processor(
              image_inputs[0],   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (1, max_patch, expected_hidden_dim),   )

          # Test batched
          lowercase__   					=			image_processor(
              __snake_case,   return_tensors="pt",   max_patches=__snake_case  ).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 			_snake_case     (   A__      ,		unittest.TestCase):
    UpperCamelCase__			:   Tuple       						=PixaStructImageProcessor if is_vision_available() else None




    def 							A__ (  self   :  Any  ):
       lowercase__   					=			PixaStructImageProcessingTester(self,   num_channels=4  )
       lowercase__   					=			3




    @property
    def 							A__ (  self   :  Optional[int]  ):
       return self.image_processor_tester.prepare_image_processor_dict()




    def 							A__ (  self   :  List[str]  ):
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       self.assertTrue(hasattr(__snake_case,   "do_normalize"  )  )
       self.assertTrue(hasattr(__snake_case,   "do_convert_rgb"  )  )




    def 							A__ (  self   :  Optional[int]  ):
       # Initialize image_processor
       lowercase__   					=			self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowercase__   					=			prepare_image_inputs(self.image_processor_tester,   equal_resolution=__snake_case  )
       for image in image_inputs:
          self.assertIsInstance(__snake_case,   Image.Image  )

       # Test not batched input
       lowercase__   					=			(
           (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
          lowercase__   					=			image_processor(
              image_inputs[0],   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (1, max_patch, expected_hidden_dim),   )

          # Test batched
          lowercase__   					=			image_processor(
              __snake_case,   return_tensors="pt",   max_patches=__snake_case  ).flattened_patches
          self.assertEqual(
              encoded_images.shape,   (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),   )









from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_						=       logging.get_logger(__name__)

lowercase_						=       {
    """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""",
}
class 			_snake_case     (   lowercase__):
				UpperCamelCase__			:   Tuple       						="""nllb-moe"""
				UpperCamelCase__			:   Dict       						=["""past_key_values"""]
				UpperCamelCase__			:   List[Any]       						={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




				def __init__(  self   :  List[str],   __lowercase   :  str=12_8112,   __lowercase   :  List[Any]=1024,   __lowercase   :  int=12,   __lowercase   :  Union[str, Any]=4096,   __lowercase   :  Union[str, Any]=16,   __lowercase   :  Tuple=12,   __lowercase   :  int=4096,   __lowercase   :  Any=16,   __lowercase   :  List[str]=0.05,   __lowercase   :  Optional[int]=0.05,   __lowercase   :  int=True,   __lowercase   :  Optional[Any]=True,   __lowercase   :  Optional[Any]="relu",   __lowercase   :  str=1024,   __lowercase   :  Optional[Any]=0.1,   __lowercase   :  List[Any]=0.1,   __lowercase   :  Union[str, Any]=0.0,   __lowercase   :  Tuple=0.02,   __lowercase   :  Optional[Any]=2,   __lowercase   :  Optional[int]=True,   __lowercase   :  List[Any]=False,   __lowercase   :  Any="float32",   __lowercase   :  Union[str, Any]=False,   __lowercase   :  Optional[int]=128,   __lowercase   :  Union[str, Any]=64,   __lowercase   :  Optional[int]=4,   __lowercase   :  Dict=4,   __lowercase   :  Any=0.001,   __lowercase   :  Optional[int]=0.001,   __lowercase   :  int="all",   __lowercase   :  Any=False,   __lowercase   :  Optional[int]=False,   __lowercase   :  Dict=1.0,   __lowercase   :  int=0.2,   __lowercase   :  str=1,   __lowercase   :  Optional[Any]=0,   __lowercase   :  Optional[int]=2,   __lowercase   :  Any=False,   **__lowercase   :  List[str],   ):
							lowercase__   					=			vocab_size
							lowercase__   					=			max_position_embeddings
							lowercase__   					=			d_model
							lowercase__   					=			encoder_ffn_dim
							lowercase__   					=			encoder_layers
							lowercase__   					=			encoder_attention_heads
							lowercase__   					=			decoder_ffn_dim
							lowercase__   					=			decoder_layers
							lowercase__   					=			decoder_attention_heads
							lowercase__   					=			dropout
							lowercase__   					=			attention_dropout
							lowercase__   					=			activation_dropout
							lowercase__   					=			activation_function
							lowercase__   					=			init_std
							lowercase__   					=			encoder_layerdrop
							lowercase__   					=			decoder_layerdrop
							lowercase__   					=			use_cache
							lowercase__   					=			encoder_layers
							lowercase__   					=			scale_embedding  # scale factor will be sqrt(d_model) if True
							lowercase__   					=			router_z_loss_coef
							lowercase__   					=			router_aux_loss_coef
							lowercase__   					=			decoder_sparse_step
							lowercase__   					=			encoder_sparse_step
							lowercase__   					=			num_experts
							lowercase__   					=			expert_capacity
							lowercase__   					=			router_bias
							if router_dtype not in ["float32", "float16", "bfloat16"]:
										raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'''  )
							lowercase__   					=			router_dtype

							lowercase__   					=			router_ignore_padding_tokens
							lowercase__   					=			batch_prioritized_routing
							lowercase__   					=			second_expert_policy
							lowercase__   					=			normalize_router_prob_before_dropping
							lowercase__   					=			moe_eval_capacity_token_fraction
							lowercase__   					=			moe_token_dropout
							lowercase__   					=			output_router_logits
							super().__init__(
							    pad_token_id=__lowercase,   bos_token_id=__lowercase,   eos_token_id=__lowercase,   is_encoder_decoder=__lowercase,   decoder_start_token_id=__lowercase,   **__lowercase,   )




