



'''simple docstring'''






import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTNeoConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
 import jax
 import jax.numpy as jnp

 from transformers.modeling_flax_pytorch_utils import (
     convert_pytorch_state_dict_to_flax,
     load_flax_weights_in_pytorch_model,
 )
 from transformers.models.gpt_neo.modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel

if is_torch_available():
 import torch



class 							lowercase :


 """simple docstring"""


 def __init__(							self						,a_						,a_=14						,a_=7						,a_=True						,a_=True						,a_=False						,a_=True						,a_=99						,a_=32						,a_=4						,a_=4						,a_=[[["global", "local"], 2]]						,a_=37						,a_="gelu"						,a_=0.1						,a_=0.1						,a_=512						,a_=7						,a_=0.02						,)	->     List[Any]:
        _UpperCAmelCase						:		Dict      =				parent
        _UpperCAmelCase						:		Dict      =				batch_size
        _UpperCAmelCase						:		Tuple      =				seq_length
        _UpperCAmelCase						:		str      =				is_training
        _UpperCAmelCase						:		Optional[Any]      =				use_input_mask
        _UpperCAmelCase						:		str      =				use_token_type_ids
        _UpperCAmelCase						:		List[str]      =				use_labels
        _UpperCAmelCase						:		Optional[int]      =				vocab_size
        _UpperCAmelCase						:		str      =				hidden_size
        _UpperCAmelCase						:		Union[str, Any]      =				num_hidden_layers
        _UpperCAmelCase						:		Tuple      =				num_attention_heads
        _UpperCAmelCase						:		List[str]      =				attention_types
        _UpperCAmelCase						:		Union[str, Any]      =				intermediate_size
        _UpperCAmelCase						:		Optional[int]      =				hidden_act
        _UpperCAmelCase						:		Union[str, Any]      =				hidden_dropout_prob
        _UpperCAmelCase						:		Optional[int]      =				attention_probs_dropout_prob
        _UpperCAmelCase						:		List[Any]      =				max_position_embeddings
        _UpperCAmelCase						:		Optional[Any]      =				window_size
        _UpperCAmelCase						:		Tuple      =				initializer_range
        _UpperCAmelCase						:		str      =				None
        _UpperCAmelCase						:		List[str]      =				vocab_size - 1
        _UpperCAmelCase						:		Union[str, Any]      =				vocab_size - 1
        _UpperCAmelCase						:		Union[str, Any]      =				vocab_size - 1







 def _snake_case				(							self							)	->     Union[str, Any]:
        _UpperCAmelCase						:		List[Any]      =				ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size							)

        _UpperCAmelCase						:		Tuple      =				None
        if self.use_input_mask:
               _UpperCAmelCase						:		List[str]      =				random_attention_mask([self.batch_size, self.seq_length]							)

        _UpperCAmelCase						:		Any      =				GPTNeoConfig(
            vocab_size=self.vocab_size						,hidden_size=self.hidden_size						,num_layers=self.num_hidden_layers						,num_heads=self.num_attention_heads						,max_position_embeddings=self.max_position_embeddings						,use_cache=lowercase_						,bos_token_id=self.bos_token_id						,eos_token_id=self.eos_token_id						,pad_token_id=self.pad_token_id						,window_size=self.window_size						,attention_types=self.attention_types						,)

        return (config, input_ids, input_mask)







 def _snake_case				(							self							)	->     List[Any]:
        _UpperCAmelCase						:		str      =				self.prepare_config_and_inputs()
        _UpperCAmelCase  ,_UpperCAmelCase  ,_UpperCAmelCase						:		Any      =				config_and_inputs
        _UpperCAmelCase						:		List[str]      =				{"""input_ids""": input_ids, """attention_mask""": attention_mask}
        return config, inputs_dict







 def _snake_case				(							self						,a_						,a_						,a_						,a_							)	->     str:
        _UpperCAmelCase						:		int      =				20
        _UpperCAmelCase						:		Any      =				model_class_name(lowercase_							)

        _UpperCAmelCase						:		str      =				model.init_cache(input_ids.shape[0]						,lowercase_							)
        _UpperCAmelCase						:		Any      =				jnp.ones((input_ids.shape[0], max_decoder_length)						,dtype="""i4"""							)

        _UpperCAmelCase						:		Optional[Any]      =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1							)[None, :]						,(input_ids.shape[0], input_ids.shape[-1] - 1)							)
        _UpperCAmelCase						:		Optional[int]      =				model(
            input_ids[:, :-1]						,attention_mask=lowercase_						,past_key_values=lowercase_						,position_ids=lowercase_						,)

        _UpperCAmelCase						:		str      =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]						,dtype="""i4"""							)
        _UpperCAmelCase						:		List[Any]      =				model(
            input_ids[:, -1:]						,attention_mask=lowercase_						,past_key_values=outputs_cache.past_key_values						,position_ids=lowercase_						,)

        _UpperCAmelCase						:		str      =				model(lowercase_							)

        _UpperCAmelCase						:		List[str]      =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])							)							)
        self.parent.assertTrue(diff < 1E-3						,msg=f'''Max diff is {diff}'''							)







 def _snake_case				(							self						,a_						,a_						,a_						,a_							)	->     int:
        _UpperCAmelCase						:		int      =				20
        _UpperCAmelCase						:		str      =				model_class_name(lowercase_							)

        _UpperCAmelCase						:		Optional[Any]      =				jnp.concatenate(
            [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])							)]						,axis=-1						,)

        _UpperCAmelCase						:		int      =				model.init_cache(input_ids.shape[0]						,lowercase_							)
        _UpperCAmelCase						:		Optional[int]      =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1							)[None, :]						,(input_ids.shape[0], input_ids.shape[-1] - 1)							)

        _UpperCAmelCase						:		str      =				model(
            input_ids[:, :-1]						,attention_mask=lowercase_						,past_key_values=lowercase_						,position_ids=lowercase_						,)
        _UpperCAmelCase						:		Optional[int]      =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]						,dtype="""i4"""							)
        _UpperCAmelCase						:		int      =				model(
            input_ids[:, -1:]						,past_key_values=outputs_cache.past_key_values						,attention_mask=lowercase_						,position_ids=lowercase_						,)

        _UpperCAmelCase						:		int      =				model(lowercase_						,attention_mask=lowercase_							)

        _UpperCAmelCase						:		int      =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])							)							)
        self.parent.assertTrue(diff < 1E-3						,msg=f'''Max diff is {diff}'''							)







@require_flax
class 							lowercase (						lowerCamelCase__      ,      lowerCamelCase__      ,      unittest.TestCase       ):


 """simple docstring"""


 UpperCAmelCase					=						(FlaxGPTNeoModel, FlaxGPTNeoForCausalLM) if is_flax_available() else ()
 UpperCAmelCase					=						(FlaxGPTNeoForCausalLM,) if is_flax_available() else ()







 def _snake_case				(							self							)	->     Any:
        _UpperCAmelCase						:		Dict      =				FlaxGPTNeoModelTester(self							)







 def _snake_case				(							self							)	->     Optional[Any]:






        for model_class_name in self.all_model_classes:
               _UpperCAmelCase  ,_UpperCAmelCase  ,_UpperCAmelCase						:		Tuple      =				self.model_tester.prepare_config_and_inputs()
               self.model_tester.check_use_cache_forward(lowercase_						,lowercase_						,lowercase_						,lowercase_							)







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






        for model_class_name in self.all_model_classes:
               _UpperCAmelCase  ,_UpperCAmelCase  ,_UpperCAmelCase						:		Tuple      =				self.model_tester.prepare_config_and_inputs()
               self.model_tester.check_use_cache_forward_with_attn_mask(
                   lowercase_						,lowercase_						,lowercase_						,lowercase_							)







 @slow
 def _snake_case				(							self							)	->     int:
        _UpperCAmelCase						:		Any      =				GPTaTokenizer.from_pretrained("""gpt2"""						,pad_token="""<|endoftext|>"""						,padding_side="""left"""							)
        _UpperCAmelCase						:		Tuple      =				tokenizer(["""Hello this is a long string""", """Hey"""]						,return_tensors="""np"""						,padding=lowercase_						,truncation=lowercase_							)

        _UpperCAmelCase						:		Optional[Any]      =				FlaxGPTNeoForCausalLM.from_pretrained("""EleutherAI/gpt-neo-125M"""							)
        _UpperCAmelCase						:		Tuple      =				False
        _UpperCAmelCase						:		Any      =				model.config.eos_token_id

        _UpperCAmelCase						:		Any      =				jax.jit(model.generate							)

        _UpperCAmelCase						:		int      =				jit_generate(
            inputs["""input_ids"""]						,attention_mask=inputs["""attention_mask"""]						,pad_token_id=tokenizer.pad_token_id							).sequences

        _UpperCAmelCase						:		Optional[int]      =				tokenizer.batch_decode(lowercase_						,skip_special_tokens=lowercase_							)

        _UpperCAmelCase						:		str      =				[
            """Hello this is a long string of text.\n\nI\'m trying to get the text of the""",
            """Hey, I\'m a little late to the party. I\'m going to""",
        ]

        self.assertListEqual(lowercase_						,lowercase_							)







 @is_pt_flax_cross_test
 def _snake_case				(							self							)	->     Any:
        _UpperCAmelCase  ,_UpperCAmelCase						:		Tuple      =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__							):
                      # prepare inputs
                      _UpperCAmelCase						:		Any      =				self._prepare_for_class(lowercase_						,lowercase_							)
                      _UpperCAmelCase						:		str      =				{k: torch.tensor(v.tolist()							) for k, v in prepared_inputs_dict.items()}

                      # load corresponding PyTorch class
                      _UpperCAmelCase						:		Tuple      =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                      _UpperCAmelCase						:		int      =				getattr(lowercase_						,lowercase_							)

                      _UpperCAmelCase  ,_UpperCAmelCase						:		int      =				pt_inputs["""input_ids"""].shape
                      _UpperCAmelCase						:		Any      =				np.random.randint(0						,seq_length - 1						,size=(batch_size,)							)
                      for batch_idx, start_index in enumerate(lowercase_							):
                             _UpperCAmelCase						:		Dict      =				0
                             _UpperCAmelCase						:		Dict      =				1
                             _UpperCAmelCase						:		Union[str, Any]      =				0
                             _UpperCAmelCase						:		int      =				1
                      _UpperCAmelCase						:		Optional[Any]      =				pt_model_class(lowercase_							).eval()
                      _UpperCAmelCase						:		Optional[Any]      =				model_class(lowercase_						,dtype=jnp.floataa							)

                      _UpperCAmelCase						:		Tuple      =				convert_pytorch_state_dict_to_flax(pt_model.state_dict()						,lowercase_							)
                      _UpperCAmelCase						:		List[str]      =				fx_state

                      with torch.no_grad():
                             _UpperCAmelCase						:		Union[str, Any]      =				pt_model(**lowercase_							).to_tuple()

                      _UpperCAmelCase						:		Optional[Any]      =				fx_model(**lowercase_							).to_tuple()
                      self.assertEqual(len(lowercase_							)						,len(lowercase_							)						,"""Output lengths differ between Flax and PyTorch"""							)
                      for fx_output, pt_output in zip(lowercase_						,lowercase_							):
                             self.assert_almost_equals(fx_output[:, -1]						,pt_output[:, -1].numpy()						,4E-2							)

                      with tempfile.TemporaryDirectory() as tmpdirname:
                             pt_model.save_pretrained(lowercase_							)
                             _UpperCAmelCase						:		List[Any]      =				model_class.from_pretrained(lowercase_						,from_pt=lowercase_							)

                      _UpperCAmelCase						:		Optional[Any]      =				fx_model_loaded(**lowercase_							).to_tuple()
                      self.assertEqual(
                          len(lowercase_							)						,len(lowercase_							)						,"""Output lengths differ between Flax and PyTorch"""							)
                      for fx_output_loaded, pt_output in zip(lowercase_						,lowercase_							):
                             self.assert_almost_equals(fx_output_loaded[:, -1]						,pt_output[:, -1].numpy()						,4E-2							)







 @is_pt_flax_cross_test
 def _snake_case				(							self							)	->     Any:
        _UpperCAmelCase  ,_UpperCAmelCase						:		Union[str, Any]      =				self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__							):
                      # prepare inputs
                      _UpperCAmelCase						:		List[Any]      =				self._prepare_for_class(lowercase_						,lowercase_							)
                      _UpperCAmelCase						:		Union[str, Any]      =				{k: torch.tensor(v.tolist()							) for k, v in prepared_inputs_dict.items()}

                      # load corresponding PyTorch class
                      _UpperCAmelCase						:		Any      =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                      _UpperCAmelCase						:		Tuple      =				getattr(lowercase_						,lowercase_							)

                      _UpperCAmelCase						:		Tuple      =				pt_model_class(lowercase_							).eval()
                      _UpperCAmelCase						:		Dict      =				model_class(lowercase_						,dtype=jnp.floataa							)

                      _UpperCAmelCase						:		Optional[Any]      =				load_flax_weights_in_pytorch_model(lowercase_						,fx_model.params							)
                      _UpperCAmelCase  ,_UpperCAmelCase						:		List[Any]      =				pt_inputs["""input_ids"""].shape
                      _UpperCAmelCase						:		Optional[Any]      =				np.random.randint(0						,seq_length - 1						,size=(batch_size,)							)
                      for batch_idx, start_index in enumerate(lowercase_							):
                             _UpperCAmelCase						:		List[str]      =				0
                             _UpperCAmelCase						:		Union[str, Any]      =				1
                             _UpperCAmelCase						:		Optional[int]      =				0
                             _UpperCAmelCase						:		List[Any]      =				1

                      # make sure weights are tied in PyTorch
                      pt_model.tie_weights()

                      with torch.no_grad():
                             _UpperCAmelCase						:		Optional[int]      =				pt_model(**lowercase_							).to_tuple()

                      _UpperCAmelCase						:		Optional[Any]      =				fx_model(**lowercase_							).to_tuple()
                      self.assertEqual(len(lowercase_							)						,len(lowercase_							)						,"""Output lengths differ between Flax and PyTorch"""							)
                      for fx_output, pt_output in zip(lowercase_						,lowercase_							):
                             self.assert_almost_equals(fx_output[:, -1]						,pt_output[:, -1].numpy()						,4E-2							)

                      with tempfile.TemporaryDirectory() as tmpdirname:
                             fx_model.save_pretrained(lowercase_							)
                             _UpperCAmelCase						:		List[str]      =				pt_model_class.from_pretrained(lowercase_						,from_flax=lowercase_							)

                      with torch.no_grad():
                             _UpperCAmelCase						:		Any      =				pt_model_loaded(**lowercase_							).to_tuple()

                      self.assertEqual(
                          len(lowercase_							)						,len(lowercase_							)						,"""Output lengths differ between Flax and PyTorch"""							)
                      for fx_output, pt_output in zip(lowercase_						,lowercase_							):
                             self.assert_almost_equals(fx_output[:, -1]						,pt_output[:, -1].numpy()						,4E-2							)







 @slow
 def _snake_case				(							self							)	->     Any:






        for model_class_name in self.all_model_classes:
               _UpperCAmelCase						:		Union[str, Any]      =				model_class_name.from_pretrained("""EleutherAI/gpt-neo-125M"""							)
               _UpperCAmelCase						:		int      =				model(np.ones((1, 1)							)							)
               self.assertIsNotNone(lowercase_							)








'''simple docstring'''






from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


A_							:				List[str]						=			logging.get_logger(__name__)  # pylint: disable=invalid-name



class 							lowercase (						_lowerCamelCase       ):


 """simple docstring"""


 UpperCAmelCase					=						["""safety_checker""", """feature_extractor"""]







 def __init__(							self						,a_						,a_						,a_						,a_						,a_						,a_						,a_						,a_ = True						,)	->     int:
        super().__init__()
        if hasattr(scheduler.config						,"""steps_offset"""							) and scheduler.config.steps_offset != 1:
               _UpperCAmelCase						:		Tuple      =				(
                   f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'''
                   f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '''
                   """to update the config accordingly as leaving `steps_offset` might led to incorrect results"""
                   """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"""
                   """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"""
                   """ file"""
               )
               deprecate("""steps_offset!=1"""						,"""1.0.0"""						,a_						,standard_warn=a_							)
               _UpperCAmelCase						:		Any      =				dict(scheduler.config							)
               _UpperCAmelCase						:		str      =				1
               _UpperCAmelCase						:		Any      =				FrozenDict(a_							)

        self.register_modules(
            vae=a_						,text_encoder=a_						,tokenizer=a_						,unet=a_						,scheduler=a_						,safety_checker=a_						,feature_extractor=a_						,)
        self.register_to_config(requires_safety_checker=a_							)







 @property
 def _snake_case				(							self							)	->     Dict[str, Any]:
        return {k: getattr(self						,a_							) for k in self.config.keys() if not k.startswith("""_"""							)}







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







 def _snake_case				(							self							)	->     Tuple:
        self.enable_attention_slicing(a_							)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_						,a_						,a_ = 0.8						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,)	->     List[Any]:
        # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
        return StableDiffusionInpaintPipelineLegacy(**self.components							)(
            prompt=a_						,image=a_						,mask_image=a_						,strength=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,output_type=a_						,return_dict=a_						,callback=a_						,)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_						,a_ = 0.8						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,**a_						,)	->     Tuple:
        # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
        return StableDiffusionImgaImgPipeline(**self.components							)(
            prompt=a_						,image=a_						,strength=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,output_type=a_						,return_dict=a_						,callback=a_						,callback_steps=a_						,)







 @torch.no_grad()
 def _snake_case				(							self						,a_						,a_ = 512						,a_ = 512						,a_ = 50						,a_ = 7.5						,a_ = None						,a_ = 1						,a_ = 0.0						,a_ = None						,a_ = None						,a_ = "pil"						,a_ = True						,a_ = None						,a_ = 1						,)	->     List[str]:
        # For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
        return StableDiffusionPipeline(**self.components							)(
            prompt=a_						,height=a_						,width=a_						,num_inference_steps=a_						,guidance_scale=a_						,negative_prompt=a_						,num_images_per_prompt=a_						,eta=a_						,generator=a_						,latents=a_						,output_type=a_						,return_dict=a_						,callback=a_						,callback_steps=a_						,)



