



import os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
				import jax
				import jax.numpy as jnp
				from flax.jax_utils import replicate
				from flax.training.common_utils import shard

				from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline







@require_flax
class   _UpperCamelCase  (       unittest.TestCase  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						with tempfile.TemporaryDirectory() as tmpdirname:
							# pipeline has Flax weights
							UpperCAmelCase_								=     FlaxDiffusionPipeline.from_pretrained(
							    """hf-internal-testing/tiny-stable-diffusion-pipe""" ,					safety_checker=__lowercase ,					cache_dir=__lowercase		)

							UpperCAmelCase_								=     [t[-1] for t in os.walk(os.path.join(__lowercase ,					os.listdir(__lowercase		)[0] ,					"""snapshots"""		)		)]
							UpperCAmelCase_								=     [item for sublist in all_root_files for item in sublist]

							# None of the downloaded files should be a PyTorch file even if we have some here:
							# https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
							assert not any(f.endswith(""".bin"""		) for f in files		)







@slow
@require_flax
class   _UpperCamelCase  (       unittest.TestCase  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  Dict		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """hf-internal-testing/tiny-stable-diffusion-pipe""" ,					safety_checker=__lowercase		)

						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.random.PRNGKey(0		)
						UpperCAmelCase_								=     4

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)

						# shard inputs and rng
						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     jax.random.split(__lowercase ,					__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)

						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images

						assert images.shape == (num_samples, 1, 64, 64, 3)
						if jax.device_count() == 8:
							assert np.abs(np.abs(images[0, 0, :2, :2, -2:] ,					dtype=np.floataa		).sum() - 4.1514745		) < 1e-3
							assert np.abs(np.abs(__lowercase ,					dtype=np.floataa		).sum() - 49947.875		) < 5e-1

						UpperCAmelCase_								=     pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]		)		)		)
						assert len(__lowercase		) == num_samples





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""flax""" ,					safety_checker=__lowercase		)

						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.random.PRNGKey(0		)
						UpperCAmelCase_								=     50

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)

						# shard inputs and rng
						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     jax.random.split(__lowercase ,					__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)

						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images

						assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:] ,					dtype=np.floataa		).sum() - 0.05652401)		) < 1e-3
							assert np.abs((np.abs(__lowercase ,					dtype=np.floataa		).sum() - 2383808.2)		) < 5e-1





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""bf16""" ,					dtype=jnp.bfloataa ,					safety_checker=__lowercase		)

						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.random.PRNGKey(0		)
						UpperCAmelCase_								=     50

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)

						# shard inputs and rng
						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     jax.random.split(__lowercase ,					__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)

						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images

						assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:] ,					dtype=np.floataa		).sum() - 0.04003906)		) < 1e-3
							assert np.abs((np.abs(__lowercase ,					dtype=np.floataa		).sum() - 2373516.75)		) < 5e-1





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""bf16""" ,					dtype=jnp.bfloataa		)

						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.random.PRNGKey(0		)
						UpperCAmelCase_								=     50

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)

						# shard inputs and rng
						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     jax.random.split(__lowercase ,					__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)

						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images

						assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:] ,					dtype=np.floataa		).sum() - 0.04003906)		) < 1e-3
							assert np.abs((np.abs(__lowercase ,					dtype=np.floataa		).sum() - 2373516.75)		) < 5e-1





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     FlaxDDIMScheduler(
						    beta_start=0.00085 ,					beta_end=0.012 ,					beta_schedule="""scaled_linear""" ,					set_alpha_to_one=__lowercase ,					steps_offset=1 ,					)

						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""bf16""" ,					dtype=jnp.bfloataa ,					scheduler=__lowercase ,					safety_checker=__lowercase ,					)
						UpperCAmelCase_								=     scheduler.create_state()

						UpperCAmelCase_								=     scheduler_state

						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.random.PRNGKey(0		)
						UpperCAmelCase_								=     50

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)

						# shard inputs and rng
						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     jax.random.split(__lowercase ,					__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)

						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images

						assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:] ,					dtype=np.floataa		).sum() - 0.045043945)		) < 1e-3
							assert np.abs((np.abs(__lowercase ,					dtype=np.floataa		).sum() - 2347693.5)		) < 5e-1





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     (
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						UpperCAmelCase_								=     jax.device_count()
						UpperCAmelCase_								=     num_samples * [prompt]
						UpperCAmelCase_								=     jax.random.split(jax.random.PRNGKey(0		) ,					__lowercase		)

						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""bf16""" ,					dtype=jnp.bfloataa ,					safety_checker=__lowercase ,					)

						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)
						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images
						assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
						UpperCAmelCase_								=     images[2, 0, 2_56, 10:17, 1]

						# With memory efficient attention
						UpperCAmelCase_						,	UpperCAmelCase_								=     FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4""" ,					revision="""bf16""" ,					dtype=jnp.bfloataa ,					safety_checker=__lowercase ,					use_memory_efficient_attention=__lowercase ,					)

						UpperCAmelCase_								=     replicate(__lowercase		)
						UpperCAmelCase_								=     pipeline.prepare_inputs(__lowercase		)
						UpperCAmelCase_								=     shard(__lowercase		)
						UpperCAmelCase_								=     pipeline(__lowercase ,					__lowercase ,					__lowercase ,					jit=__lowercase		).images
						assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3)
						UpperCAmelCase_								=     images[2, 0, 2_56, 10:17, 1]

						# I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
						# over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
						assert abs(slice_eff - slice		).max() < 1e-2









import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
				from transformers.models.rag.configuration_rag import RagConfig
				from transformers.models.rag.tokenization_rag import RagTokenizer







@require_faiss
@require_torch
class   _UpperCamelCase  (       A_  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     tempfile.mkdtemp()
						UpperCAmelCase_								=     8

						# DPR tok
						UpperCAmelCase_								=     [
						    """[UNK]""",
						    """[CLS]""",
						    """[SEP]""",
						    """[PAD]""",
						    """[MASK]""",
						    """want""",
						    """##want""",
						    """##ed""",
						    """wa""",
						    """un""",
						    """runn""",
						    """##ing""",
						    """,""",
						    """low""",
						    """lowest""",
						]
						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					DPR_VOCAB_FILES_NAMES["""vocab_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as vocab_writer:
							vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

						# BART tok
						UpperCAmelCase_								=     [
						    """l""",
						    """o""",
						    """w""",
						    """e""",
						    """r""",
						    """s""",
						    """t""",
						    """i""",
						    """d""",
						    """n""",
						    """\u0120""",
						    """\u0120l""",
						    """\u0120n""",
						    """\u0120lo""",
						    """\u0120low""",
						    """er""",
						    """\u0120lowest""",
						    """\u0120newer""",
						    """\u0120wider""",
						    """<unk>""",
						]
						UpperCAmelCase_								=     dict(zip(__lowercase ,					range(len(__lowercase		)		)		)		)
						UpperCAmelCase_								=     ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
						UpperCAmelCase_								=     {"""unk_token""": """<unk>"""}

						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""vocab_file"""]		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""merges_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write(json.dumps(__lowercase		) + """\n"""		)
						with open(self.merges_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write("""\n""".join(__lowercase		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						shutil.rmtree(self.tmpdirname		)





					@require_tokenizers
					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""rag_tokenizer"""		)
						UpperCAmelCase_								=     RagConfig(question_encoder=DPRConfig().to_dict() ,					generator=BartConfig().to_dict()		)
						UpperCAmelCase_								=     RagTokenizer(question_encoder=self.get_dpr_tokenizer() ,					generator=self.get_bart_tokenizer()		)
						rag_config.save_pretrained(__lowercase		)
						rag_tokenizer.save_pretrained(__lowercase		)
						UpperCAmelCase_								=     RagTokenizer.from_pretrained(__lowercase ,					config=__lowercase		)
						self.assertIsInstance(new_rag_tokenizer.question_encoder ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() ,					rag_tokenizer.question_encoder.get_vocab()		)
						self.assertIsInstance(new_rag_tokenizer.generator ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.generator.get_vocab() ,					rag_tokenizer.generator.get_vocab()		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-token-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  List[str]		):






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)


