




from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers.models.xglm.modeling_tf_xglm import (
     TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFXGLMForCausalLM,
     TFXGLMModel,
 )



@require_tf
class       a					:

     '''simple docstring'''





     lowerCAmelCase    :	Union[str, Any]       		=  XGLMConfig
     lowerCAmelCase    :	Union[str, Any]       		=  {}
     lowerCAmelCase    :	Union[str, Any]       		=  'gelu'
     def __init__(     self       :      List[Any] ,   __snake_case       :      List[str] ,   __snake_case       :      List[Any]=14 ,   __snake_case       :      List[str]=7 ,   __snake_case       :      Optional[int]=True ,   __snake_case       :      Dict=True ,   __snake_case       :      List[str]=True ,   __snake_case       :      Dict=99 ,   __snake_case       :      str=32 ,   __snake_case       :      List[str]=2 ,   __snake_case       :      Union[str, Any]=4 ,   __snake_case       :      Optional[Any]=37 ,   __snake_case       :      Optional[int]="gelu" ,   __snake_case       :      List[str]=0.1 ,   __snake_case       :      Union[str, Any]=0.1 ,   __snake_case       :      Union[str, Any]=5_12 ,   __snake_case       :      str=0.02 ,   ):
           UpperCAmelCase_										=					parent
           UpperCAmelCase_										=					batch_size
           UpperCAmelCase_										=					seq_length
           UpperCAmelCase_										=					is_training
           UpperCAmelCase_										=					use_input_mask
           UpperCAmelCase_										=					use_labels
           UpperCAmelCase_										=					vocab_size
           UpperCAmelCase_										=					d_model
           UpperCAmelCase_										=					num_hidden_layers
           UpperCAmelCase_										=					num_attention_heads
           UpperCAmelCase_										=					ffn_dim
           UpperCAmelCase_										=					activation_function
           UpperCAmelCase_										=					activation_dropout
           UpperCAmelCase_										=					attention_dropout
           UpperCAmelCase_										=					max_position_embeddings
           UpperCAmelCase_										=					initializer_range
           UpperCAmelCase_										=					None
           UpperCAmelCase_										=					0
           UpperCAmelCase_										=					2
           UpperCAmelCase_										=					1
     def   lowerCamelCase_       (     self       :      Dict    ):
           return XGLMConfig.from_pretrained('''facebook/xglm-564M'''    )
     def   lowerCamelCase_       (     self       :      List[str]    ):
           UpperCAmelCase_										=					tf.clip_by_value(
               ids_tensor([self.batch_size, self.seq_length] ,   self.vocab_size    ) ,   clip_value_min=0 ,   clip_value_max=3    )

           UpperCAmelCase_										=					None
           if self.use_input_mask:
                 UpperCAmelCase_										=					random_attention_mask([self.batch_size, self.seq_length]    )

           UpperCAmelCase_										=					self.get_config()

           UpperCAmelCase_										=					floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,   2    )

           return (
               config,
               input_ids,
               input_mask,
               head_mask,
           )
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
           return XGLMConfig(
               vocab_size=self.vocab_size ,   d_model=self.hidden_size ,   num_layers=self.num_hidden_layers ,   attention_heads=self.num_attention_heads ,   ffn_dim=self.ffn_dim ,   activation_function=self.activation_function ,   activation_dropout=self.activation_dropout ,   attention_dropout=self.attention_dropout ,   max_position_embeddings=self.max_position_embeddings ,   initializer_range=self.initializer_range ,   use_cache=__snake_case ,   bos_token_id=self.bos_token_id ,   eos_token_id=self.eos_token_id ,   pad_token_id=self.pad_token_id ,   return_dict=__snake_case ,   )




     def   lowerCamelCase_       (     self       :      Optional[int]    ):
           UpperCAmelCase_										=					self.prepare_config_and_inputs()

           (
               (
               UpperCAmelCase_							
           )			,							(
               UpperCAmelCase_							
           )			,							(
               UpperCAmelCase_							
           )			,							(
               UpperCAmelCase_							
           )			,														
           )										=					config_and_inputs

           UpperCAmelCase_										=					{
               '''input_ids''': input_ids,
               '''head_mask''': head_mask,
           }

           return config, inputs_dict



@require_tf
class       a					(       _A     ,       _A     ,       unittest.TestCase      ):

     '''simple docstring'''





     lowerCAmelCase    :	Tuple       		=  (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
     lowerCAmelCase    :	Dict       		=  (TFXGLMForCausalLM,) if is_tf_available() else ()
     lowerCAmelCase    :	List[str]       		=  (
         {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
     )
     lowerCAmelCase    :	Tuple       		=  False
     lowerCAmelCase    :	int       		=  False
     lowerCAmelCase    :	Dict       		=  False
     def   lowerCamelCase_       (     self       :      Optional[Any]    ):
           UpperCAmelCase_										=					TFXGLMModelTester(self    )
           UpperCAmelCase_										=					ConfigTester(self ,   config_class=__snake_case ,   n_embd=37    )
     def   lowerCamelCase_       (     self       :      int    ):
           self.config_tester.run_common_tests()
     @slow
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
           for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 UpperCAmelCase_										=					TFXGLMModel.from_pretrained(__snake_case    )
                 self.assertIsNotNone(__snake_case    )




     @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''    )
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
           super().test_resize_token_embeddings()



@require_tf
class       a					(       unittest.TestCase      ):

     '''simple docstring'''





     @slow
     def   lowerCamelCase_       (     self       :      Tuple ,   __snake_case       :      int=True    ):
           UpperCAmelCase_										=					TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )
           UpperCAmelCase_										=					tf.convert_to_tensor([[2, 2_68, 98_65]] ,   dtype=tf.intaa    )  # The dog
           # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
           # fmt: off
           UpperCAmelCase_										=					[2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81]
           # fmt: on
           UpperCAmelCase_										=					model.generate(__snake_case ,   do_sample=__snake_case ,   num_beams=1    )
           if verify_outputs:
                 self.assertListEqual(output_ids[0].numpy().tolist() ,   __snake_case    )
     @slow
     def   lowerCamelCase_       (     self       :      Any    ):
           UpperCAmelCase_										=					XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''    )
           UpperCAmelCase_										=					TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )

           tf.random.set_seed(0    )
           UpperCAmelCase_										=					tokenizer('''Today is a nice day and''' ,   return_tensors='''tf'''    )
           UpperCAmelCase_										=					tokenized.input_ids
           # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
           with tf.device(''':/CPU:0'''    ):
                 UpperCAmelCase_										=					model.generate(__snake_case ,   do_sample=__snake_case ,   seed=[7, 0]    )
           UpperCAmelCase_										=					tokenizer.decode(output_ids[0] ,   skip_special_tokens=__snake_case    )

           UpperCAmelCase_										=					(
               '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
           )
           self.assertEqual(__snake_case ,   __snake_case    )




     @slow
     def   lowerCamelCase_       (     self       :      Dict    ):
           UpperCAmelCase_										=					TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )
           UpperCAmelCase_										=					XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''    )

           UpperCAmelCase_										=					'''left'''

           # use different length sentences to test batching
           UpperCAmelCase_										=					[
               '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
               '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
               '''regardless of whether left padding is applied or not. When''',
               '''Hello, my dog is a little''',
           ]

           UpperCAmelCase_										=					tokenizer(__snake_case ,   return_tensors='''tf''' ,   padding=__snake_case    )
           UpperCAmelCase_										=					inputs['''input_ids''']

           UpperCAmelCase_										=					model.generate(input_ids=__snake_case ,   attention_mask=inputs['''attention_mask'''] ,   max_new_tokens=12    )

           UpperCAmelCase_										=					tokenizer(sentences[0] ,   return_tensors='''tf'''    ).input_ids
           UpperCAmelCase_										=					model.generate(input_ids=__snake_case ,   max_new_tokens=12    )

           UpperCAmelCase_										=					tokenizer(sentences[1] ,   return_tensors='''tf'''    ).input_ids
           UpperCAmelCase_										=					model.generate(input_ids=__snake_case ,   max_new_tokens=12    )

           UpperCAmelCase_										=					tokenizer.batch_decode(__snake_case ,   skip_special_tokens=__snake_case    )
           UpperCAmelCase_										=					tokenizer.decode(output_non_padded[0] ,   skip_special_tokens=__snake_case    )
           UpperCAmelCase_										=					tokenizer.decode(output_padded[0] ,   skip_special_tokens=__snake_case    )

           UpperCAmelCase_										=					[
               '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
               '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
               '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '''
               '''a single''',
               '''Hello, my dog is a little bit of a shy one, but he is very friendly''',
           ]
           self.assertListEqual(__snake_case ,   __snake_case    )
           self.assertListEqual(__snake_case ,   [non_padded_sentence, padded_sentence]    )











from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase      			=						logging.get_logger(__name__)



class       a					(       _A      ):

     '''simple docstring'''





     lowerCAmelCase    :	List[Any]       		=  ['pixel_values']
     def __init__(     self       :      Any ,   __snake_case       :      bool = True ,   __snake_case       :      Dict[str, int] = None ,   __snake_case       :      PILImageResampling = PILImageResampling.BICUBIC ,   __snake_case       :      bool = True ,   __snake_case       :      Dict[str, int] = None ,   __snake_case       :      bool = True ,   __snake_case       :      Union[int, float] = 1 / 2_55 ,   __snake_case       :      bool = True ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD ,   **__snake_case       :      Optional[Any] ,   ):
         super().__init__(**__snake_case    )
         UpperCAmelCase_										=					size if size is not None else {'''shortest_edge''': 2_24}
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         UpperCAmelCase_										=					crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   param_name='''crop_size'''    )

         UpperCAmelCase_										=					do_resize
         UpperCAmelCase_										=					size
         UpperCAmelCase_										=					resample
         UpperCAmelCase_										=					do_center_crop
         UpperCAmelCase_										=					crop_size
         UpperCAmelCase_										=					do_rescale
         UpperCAmelCase_										=					rescale_factor
         UpperCAmelCase_										=					do_normalize
         UpperCAmelCase_										=					image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         UpperCAmelCase_										=					image_std if image_std is not None else IMAGENET_DEFAULT_STD
     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      np.ndarray ,   __snake_case       :      Dict[str, int] ,   __snake_case       :      PILImageResampling = PILImageResampling.BICUBIC ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Tuple ,   ):
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
         if "shortest_edge" in size:
             UpperCAmelCase_										=					int((2_56 / 2_24) * size['''shortest_edge''']    )
             UpperCAmelCase_										=					get_resize_output_image_size(__snake_case ,   size=__snake_case ,   default_to_square=__snake_case    )
             UpperCAmelCase_										=					{'''height''': output_size[0], '''width''': output_size[1]}
         if "height" not in size_dict or "width" not in size_dict:
             raise ValueError(
                 F'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'    )
         return resize(
             __snake_case ,   size=(size_dict['''height'''], size_dict['''width''']) ,   resample=__snake_case ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      Tuple ,   __snake_case       :      np.ndarray ,   __snake_case       :      Dict[str, int] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Optional[int] ,   ):
         UpperCAmelCase_										=					get_size_dict(__snake_case    )
         if "height" not in size or "width" not in size:
             raise ValueError(F'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'    )
         return center_crop(__snake_case ,   size=(size['''height'''], size['''width''']) ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      Optional[Any] ,   __snake_case       :      np.ndarray ,   __snake_case       :      Union[int, float] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      List[Any] ,   ):
         return rescale(__snake_case ,   scale=__snake_case ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      np.ndarray ,   __snake_case       :      Union[float, List[float]] ,   __snake_case       :      Union[float, List[float]] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Union[str, Any] ,   ):
         return normalize(__snake_case ,   mean=__snake_case ,   std=__snake_case ,   data_format=__snake_case ,   **__snake_case    )




     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      ImageInput ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Dict[str, int]] = None ,   __snake_case       :      PILImageResampling = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Dict[str, int]] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[float] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = None ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = None ,   __snake_case       :      Optional[TensorType] = None ,   __snake_case       :      ChannelDimension = ChannelDimension.FIRST ,   **__snake_case       :      List[str] ,   ):
         UpperCAmelCase_										=					do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase_										=					resample if resample is not None else self.resample
         UpperCAmelCase_										=					do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase_										=					do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase_										=					rescale_factor if rescale_factor is not None else self.rescale_factor
         UpperCAmelCase_										=					do_normalize if do_normalize is not None else self.do_normalize
         UpperCAmelCase_										=					image_mean if image_mean is not None else self.image_mean
         UpperCAmelCase_										=					image_std if image_std is not None else self.image_std

         UpperCAmelCase_										=					size if size is not None else self.size
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         UpperCAmelCase_										=					crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   param_name='''crop_size'''    )

         UpperCAmelCase_										=					make_list_of_images(__snake_case    )

         if not valid_images(__snake_case    ):
             raise ValueError(
                 '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                 '''torch.Tensor, tf.Tensor or jax.ndarray.'''    )

         if do_resize and size is None:
             raise ValueError('''Size must be specified if do_resize is True.'''    )

         if do_center_crop and crop_size is None:
             raise ValueError('''Crop size must be specified if do_center_crop is True.'''    )

         if do_rescale and rescale_factor is None:
             raise ValueError('''Rescale factor must be specified if do_rescale is True.'''    )

         if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('''Image mean and std must be specified if do_normalize is True.'''    )

         # All transformations expect numpy arrays.
         UpperCAmelCase_										=					[to_numpy_array(__snake_case    ) for image in images]

         if do_resize:
             UpperCAmelCase_										=					[self.resize(__snake_case ,   __snake_case ,   __snake_case    ) for image in images]

         if do_center_crop:
             UpperCAmelCase_										=					[self.center_crop(__snake_case ,   __snake_case    ) for image in images]

         if do_rescale:
             UpperCAmelCase_										=					[self.rescale(__snake_case ,   __snake_case    ) for image in images]

         if do_normalize:
             UpperCAmelCase_										=					[self.normalize(__snake_case ,   __snake_case ,   __snake_case    ) for image in images]

         UpperCAmelCase_										=					[to_channel_dimension_format(__snake_case ,   __snake_case    ) for image in images]

         UpperCAmelCase_										=					{'''pixel_values''': images}
         return BatchFeature(data=__snake_case ,   tensor_type=__snake_case    )





