


'''simple docstring'''



import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import DiffusionPipeline
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import logging


A__						:   Optional[Any]				=    logging.get_logger(__name__)  # pylint: disable=invalid-name





class   UpperCAmelCase_    (_UpperCAmelCase    ):





    """simple docstring"""






    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	)							->	Optional[Any]:
         super().__init__()
         self.register_modules(
             vae=SCREAMING_SNAKE_CASE_     ,	text_encoder=SCREAMING_SNAKE_CASE_     ,	tokenizer=SCREAMING_SNAKE_CASE_     ,	unet=SCREAMING_SNAKE_CASE_     ,	scheduler=SCREAMING_SNAKE_CASE_     ,	safety_checker=SCREAMING_SNAKE_CASE_     ,	feature_extractor=SCREAMING_SNAKE_CASE_     ,	)







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_ = "auto"      )							->	int:
         if slice_size == "auto":
              # half the attention head size is usually a good trade-off between
              # speed and memory
              __lowerCamelCase  :      Optional[int]														=						self.unet.config.attention_head_dim // 2
         self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	List[str]:
         self.enable_attention_slicing(SCREAMING_SNAKE_CASE_      )







    @torch.no_grad()
    def __call__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = 5_12     ,	SCREAMING_SNAKE_CASE_ = 5_12     ,	SCREAMING_SNAKE_CASE_ = 50     ,	SCREAMING_SNAKE_CASE_ = 7.5     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = 1     ,	SCREAMING_SNAKE_CASE_ = 0.0     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = "pil"     ,	SCREAMING_SNAKE_CASE_ = True     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = 1     ,	SCREAMING_SNAKE_CASE_ = None     ,	**SCREAMING_SNAKE_CASE_     ,	)							->	Any:

         if isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ):
              __lowerCamelCase  :      Any														=						1
         elif isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ):
              __lowerCamelCase  :      List[str]														=						len(SCREAMING_SNAKE_CASE_      )
         else:
              raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_      )}'      )

         if height % 8 != 0 or width % 8 != 0:
              raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.'      )

         if (callback_steps is None) or (
             callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ) or callback_steps <= 0)
         ):
              raise ValueError(
                  f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
                  f' {type(SCREAMING_SNAKE_CASE_      )}.'      )

         # get prompt text embeddings
         __lowerCamelCase  :      str														=						self.tokenizer(
             SCREAMING_SNAKE_CASE_     ,	padding='max_length'     ,	max_length=self.tokenizer.model_max_length     ,	return_tensors='pt'     ,	)
         __lowerCamelCase  :      Optional[int]														=						text_inputs.input_ids

         if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
              __lowerCamelCase  :      Optional[int]														=						self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]      )
              logger.warning(
                  'The following part of your input was truncated because CLIP can only handle sequences up to'
                  f' {self.tokenizer.model_max_length} tokens: {removed_text}'      )
              __lowerCamelCase  :      int														=						text_input_ids[:, : self.tokenizer.model_max_length]

         if text_embeddings is None:
              __lowerCamelCase  :      Optional[Any]														=						self.text_encoder(text_input_ids.to(self.device      )      )[0]

         # duplicate text embeddings for each generation per prompt, using mps friendly method
         __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      Dict														=						text_embeddings.shape
         __lowerCamelCase  :      Tuple														=						text_embeddings.repeat(1     ,	SCREAMING_SNAKE_CASE_     ,	1      )
         __lowerCamelCase  :      Tuple														=						text_embeddings.view(bs_embed * num_images_per_prompt     ,	SCREAMING_SNAKE_CASE_     ,	-1      )

         # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
         # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
         # corresponds to doing no classifier free guidance.
         __lowerCamelCase  :      Optional[Any]														=						guidance_scale > 1.0
         # get unconditional embeddings for classifier free guidance
         if do_classifier_free_guidance:
              __lowerCamelCase  :      List[str]
              if negative_prompt is None:
                   __lowerCamelCase  :      Union[str, Any]														=						['']
              elif type(SCREAMING_SNAKE_CASE_      ) is not type(SCREAMING_SNAKE_CASE_      ):
                   raise TypeError(
                       f'`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_      )} !='
                       f' {type(SCREAMING_SNAKE_CASE_      )}.'      )
              elif isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ):
                   __lowerCamelCase  :      int														=						[negative_prompt]
              elif batch_size != len(SCREAMING_SNAKE_CASE_      ):
                   raise ValueError(
                       f'`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_      )}, but `prompt`:'
                       f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'
                       ' the batch size of `prompt`.'      )
              else:
                   __lowerCamelCase  :      Tuple														=						negative_prompt

              __lowerCamelCase  :      str														=						text_input_ids.shape[-1]
              __lowerCamelCase  :      Optional[Any]														=						self.tokenizer(
                  SCREAMING_SNAKE_CASE_     ,	padding='max_length'     ,	max_length=SCREAMING_SNAKE_CASE_     ,	truncation=SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'     ,	)
              __lowerCamelCase  :      Tuple														=						self.text_encoder(uncond_input.input_ids.to(self.device      )      )[0]

              # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
              __lowerCamelCase  :      int														=						uncond_embeddings.shape[1]
              __lowerCamelCase  :      Any														=						uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	1      )
              __lowerCamelCase  :      int														=						uncond_embeddings.view(batch_size * num_images_per_prompt     ,	SCREAMING_SNAKE_CASE_     ,	-1      )

              # For classifier free guidance, we need to do two forward passes.
              # Here we concatenate the unconditional and text embeddings into a single batch
              # to avoid doing two forward passes
              __lowerCamelCase  :      Dict														=						torch.cat([uncond_embeddings, text_embeddings]      )

         # get the initial random noise unless the user supplied it

         # Unlike in other pipelines, latents need to be generated in the target device
         # for 1-to-1 results reproducibility with the CompVis implementation.
         # However this currently doesn't work in `mps`.
         __lowerCamelCase  :      List[Any]														=						(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
         __lowerCamelCase  :      List[str]														=						(batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
         __lowerCamelCase  :      Any														=						text_embeddings.dtype
         if latents is None:
              if self.device.type == "mps":
                   # randn does not exist on mps
                   __lowerCamelCase  :      Any														=						torch.randn(
                       SCREAMING_SNAKE_CASE_     ,	generator=SCREAMING_SNAKE_CASE_     ,	device='cpu'     ,	dtype=SCREAMING_SNAKE_CASE_      ).to(self.device      )
                   __lowerCamelCase  :      Optional[int]														=						torch.randn(SCREAMING_SNAKE_CASE_     ,	generator=SCREAMING_SNAKE_CASE_     ,	device='cpu'     ,	dtype=SCREAMING_SNAKE_CASE_      ).to(
                       self.device      )
              else:
                   __lowerCamelCase  :      int														=						torch.randn(
                       SCREAMING_SNAKE_CASE_     ,	generator=SCREAMING_SNAKE_CASE_     ,	device=self.device     ,	dtype=SCREAMING_SNAKE_CASE_      )
                   __lowerCamelCase  :      List[Any]														=						torch.randn(SCREAMING_SNAKE_CASE_     ,	generator=SCREAMING_SNAKE_CASE_     ,	device=self.device     ,	dtype=SCREAMING_SNAKE_CASE_      )
         else:
              if latents_reference.shape != latents_shape:
                   raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}'      )
              __lowerCamelCase  :      Optional[int]														=						latents_reference.to(self.device      )
              __lowerCamelCase  :      Optional[Any]														=						latents.to(self.device      )

         # This is the key part of the pipeline where we
         # try to ensure that the generated images w/ the same seed
         # but different sizes actually result in similar images
         __lowerCamelCase  :      List[str]														=						(latents_shape[3] - latents_shape_reference[3]) // 2
         __lowerCamelCase  :      str														=						(latents_shape[2] - latents_shape_reference[2]) // 2
         __lowerCamelCase  :      str														=						latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
         __lowerCamelCase  :      Any														=						latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
         __lowerCamelCase  :      Dict														=						0 if dx < 0 else dx
         __lowerCamelCase  :      Dict														=						0 if dy < 0 else dy
         __lowerCamelCase  :      int														=						max(-dx     ,	0      )
         __lowerCamelCase  :      List[Any]														=						max(-dy     ,	0      )
         # import pdb
         # pdb.set_trace()
         __lowerCamelCase  :      List[str]														=						latents_reference[:, :, dy : dy + h, dx : dx + w]

         # set timesteps
         self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_      )

         # Some schedulers like PNDM have timesteps as arrays
         # It's more optimized to move all timesteps to correct device beforehand
         __lowerCamelCase  :      Union[str, Any]														=						self.scheduler.timesteps.to(self.device      )

         # scale the initial noise by the standard deviation required by the scheduler
         __lowerCamelCase  :      Tuple														=						latents * self.scheduler.init_noise_sigma

         # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
         # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
         # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
         # and should be between [0, 1]
         __lowerCamelCase  :      str														=						'eta' in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
         __lowerCamelCase  :      Any														=						{}
         if accepts_eta:
              __lowerCamelCase  :      List[Any]														=						eta

         for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_      )      ):
              # expand the latents if we are doing classifier free guidance
              __lowerCamelCase  :      Any														=						torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
              __lowerCamelCase  :      Dict														=						self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )

              # predict the noise residual
              __lowerCamelCase  :      List[Any]														=						self.unet(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	encoder_hidden_states=SCREAMING_SNAKE_CASE_      ).sample

              # perform guidance
              if do_classifier_free_guidance:
                   __lowerCamelCase							,			__lowerCamelCase  :      int														=						noise_pred.chunk(2      )
                   __lowerCamelCase  :      str														=						noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

              # compute the previous noisy sample x_t -> x_t-1
              __lowerCamelCase  :      int														=						self.scheduler.step(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      ).prev_sample

              # call the callback, if provided
              if callback is not None and i % callback_steps == 0:
                   callback(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      str														=						1 / 0.1_8_2_1_5 * latents
         __lowerCamelCase  :      str														=						self.vae.decode(SCREAMING_SNAKE_CASE_      ).sample

         __lowerCamelCase  :      Optional[Any]														=						(image / 2 + 0.5).clamp(0     ,	1      )

         # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
         __lowerCamelCase  :      Dict														=						image.cpu().permute(0     ,	2     ,	3     ,	1      ).float().numpy()

         if self.safety_checker is not None:
              __lowerCamelCase  :      List[str]														=						self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_      )     ,	return_tensors='pt'      ).to(
                  self.device      )
              __lowerCamelCase							,			__lowerCamelCase  :      List[Any]														=						self.safety_checker(
                  images=SCREAMING_SNAKE_CASE_     ,	clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype      )      )
         else:
              __lowerCamelCase  :      str														=						None

         if output_type == "pil":
              __lowerCamelCase  :      Union[str, Any]														=						self.numpy_to_pil(SCREAMING_SNAKE_CASE_      )

         if not return_dict:
              return (image, has_nsfw_concept)

         return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_     ,	nsfw_content_detected=SCREAMING_SNAKE_CASE_      )










'''simple docstring'''



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





    """simple docstring"""






    lowerCamelCase    :   Dict					=     XGLMConfig
    lowerCamelCase    :   List[str]					=     {}
    lowerCamelCase    :   Union[str, Any]					=     'gelu'







    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=14     ,	SCREAMING_SNAKE_CASE_=7     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=99     ,	SCREAMING_SNAKE_CASE_=32     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=37     ,	SCREAMING_SNAKE_CASE_="gelu"     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=5_12     ,	SCREAMING_SNAKE_CASE_=0.0_2     ,	)							->	Any:
         __lowerCamelCase  :      int														=						parent
         __lowerCamelCase  :      Optional[int]														=						batch_size
         __lowerCamelCase  :      Optional[Any]														=						seq_length
         __lowerCamelCase  :      Optional[int]														=						is_training
         __lowerCamelCase  :      str														=						use_input_mask
         __lowerCamelCase  :      Dict														=						use_labels
         __lowerCamelCase  :      Union[str, Any]														=						vocab_size
         __lowerCamelCase  :      List[Any]														=						d_model
         __lowerCamelCase  :      List[Any]														=						num_hidden_layers
         __lowerCamelCase  :      List[Any]														=						num_attention_heads
         __lowerCamelCase  :      Optional[Any]														=						ffn_dim
         __lowerCamelCase  :      List[Any]														=						activation_function
         __lowerCamelCase  :      List[Any]														=						activation_dropout
         __lowerCamelCase  :      List[Any]														=						attention_dropout
         __lowerCamelCase  :      Union[str, Any]														=						max_position_embeddings
         __lowerCamelCase  :      Tuple														=						initializer_range
         __lowerCamelCase  :      int														=						None
         __lowerCamelCase  :      int														=						0
         __lowerCamelCase  :      Tuple														=						2
         __lowerCamelCase  :      Tuple														=						1







    def  lowercase_							(				self      )							->	Any:
         return XGLMConfig.from_pretrained('facebook/xglm-564M'      )







    def  lowercase_							(				self      )							->	Tuple:
         __lowerCamelCase  :      Optional[Any]														=						tf.clip_by_value(
             ids_tensor([self.batch_size, self.seq_length]     ,	self.vocab_size      )     ,	clip_value_min=0     ,	clip_value_max=3      )

         __lowerCamelCase  :      Optional[int]														=						None
         if self.use_input_mask:
              __lowerCamelCase  :      Any														=						random_attention_mask([self.batch_size, self.seq_length]      )

         __lowerCamelCase  :      str														=						self.get_config()

         __lowerCamelCase  :      List[Any]														=						floats_tensor([self.num_hidden_layers, self.num_attention_heads]     ,	2      )

         return (
             config,
             input_ids,
             input_mask,
             head_mask,
         )







    def  lowercase_							(				self      )							->	Optional[int]:
         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=SCREAMING_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=SCREAMING_SNAKE_CASE_     ,	)







    def  lowercase_							(				self      )							->	str:
         __lowerCamelCase  :      List[Any]														=						self.prepare_config_and_inputs()

         (
             (
             __lowerCamelCase
         )							,			(
             __lowerCamelCase
         )							,			(
             __lowerCamelCase
         )							,			(
             __lowerCamelCase
         )							,			
         )  :      str														=						config_and_inputs

         __lowerCamelCase  :      Union[str, Any]														=						{
             'input_ids': input_ids,
             'head_mask': head_mask,
         }

         return config, inputs_dict







@require_tf
class   UpperCAmelCase_    (_UpperCAmelCase   ,						_UpperCAmelCase   ,						unittest.TestCase    ):





    """simple docstring"""






    lowerCamelCase    :   Optional[Any]					=     (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
    lowerCamelCase    :   List[Any]					=     (TFXGLMForCausalLM,) if is_tf_available() else ()
    lowerCamelCase    :   Any					=     (
        {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
    )
    lowerCamelCase    :   List[Any]					=     False
    lowerCamelCase    :   Dict					=     False
    lowerCamelCase    :   Union[str, Any]					=     False







    def  lowercase_							(				self      )							->	List[Any]:
         __lowerCamelCase  :      str														=						TFXGLMModelTester(self      )
         __lowerCamelCase  :      List[Any]														=						ConfigTester(self     ,	config_class=SCREAMING_SNAKE_CASE_     ,	n_embd=37      )







    def  lowercase_							(				self      )							->	Dict:
         self.config_tester.run_common_tests()







    @slow
    def  lowercase_							(				self      )							->	Optional[int]:
         for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowerCamelCase  :      Optional[Any]														=						TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE_      )
              self.assertIsNotNone(SCREAMING_SNAKE_CASE_      )







    @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.'      )
    def  lowercase_							(				self      )							->	Any:
         super().test_resize_token_embeddings()







@require_tf
class   UpperCAmelCase_    (unittest.TestCase    ):





    """simple docstring"""






    @slow
    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_=True      )							->	List[str]:
         __lowerCamelCase  :      Optional[Any]														=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'      )
         __lowerCamelCase  :      int														=						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
         __lowerCamelCase  :      Optional[int]														=						[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
         __lowerCamelCase  :      Any														=						model.generate(SCREAMING_SNAKE_CASE_     ,	do_sample=SCREAMING_SNAKE_CASE_     ,	num_beams=1      )
         if verify_outputs:
              self.assertListEqual(output_ids[0].numpy().tolist()     ,	SCREAMING_SNAKE_CASE_      )







    @slow
    def  lowercase_							(				self      )							->	int:
         __lowerCamelCase  :      Any														=						XGLMTokenizer.from_pretrained('facebook/xglm-564M'      )
         __lowerCamelCase  :      Tuple														=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'      )

         tf.random.set_seed(0      )
         __lowerCamelCase  :      List[Any]														=						tokenizer('Today is a nice day and'     ,	return_tensors='tf'      )
         __lowerCamelCase  :      int														=						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'      ):
              __lowerCamelCase  :      Tuple														=						model.generate(SCREAMING_SNAKE_CASE_     ,	do_sample=SCREAMING_SNAKE_CASE_     ,	seed=[7, 0]      )
         __lowerCamelCase  :      Optional[Any]														=						tokenizer.decode(output_ids[0]     ,	skip_special_tokens=SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      Union[str, Any]														=						(
             'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'
         )
         self.assertEqual(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )







    @slow
    def  lowercase_							(				self      )							->	int:
         __lowerCamelCase  :      Tuple														=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'      )
         __lowerCamelCase  :      Any														=						XGLMTokenizer.from_pretrained('facebook/xglm-564M'      )

         __lowerCamelCase  :      Any														=						'left'

         # use different length sentences to test batching
         __lowerCamelCase  :      Any														=						[
             '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',
         ]

         __lowerCamelCase  :      Any														=						tokenizer(SCREAMING_SNAKE_CASE_     ,	return_tensors='tf'     ,	padding=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Optional[int]														=						inputs['input_ids']

         __lowerCamelCase  :      str														=						model.generate(input_ids=SCREAMING_SNAKE_CASE_     ,	attention_mask=inputs['attention_mask']     ,	max_new_tokens=12      )

         __lowerCamelCase  :      Optional[int]														=						tokenizer(sentences[0]     ,	return_tensors='tf'      ).input_ids
         __lowerCamelCase  :      int														=						model.generate(input_ids=SCREAMING_SNAKE_CASE_     ,	max_new_tokens=12      )

         __lowerCamelCase  :      Optional[Any]														=						tokenizer(sentences[1]     ,	return_tensors='tf'      ).input_ids
         __lowerCamelCase  :      Optional[Any]														=						model.generate(input_ids=SCREAMING_SNAKE_CASE_     ,	max_new_tokens=12      )

         __lowerCamelCase  :      Union[str, Any]														=						tokenizer.batch_decode(SCREAMING_SNAKE_CASE_     ,	skip_special_tokens=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Union[str, Any]														=						tokenizer.decode(output_non_padded[0]     ,	skip_special_tokens=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Union[str, Any]														=						tokenizer.decode(output_padded[0]     ,	skip_special_tokens=SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      Optional[int]														=						[
             '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(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         self.assertListEqual(SCREAMING_SNAKE_CASE_     ,	[non_padded_sentence, padded_sentence]      )






