




import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


UpperCamelCase__    			=			"""bart"""
UpperCamelCase__    			=			True







@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_     )
def 	_a      (						):
					if LOAD_DENSE_INDEX:
										__lowerCAmelCase				   =       AutoTokenizer.from_pretrained("yjernite/retribert-base-uncased"     )
										__lowerCAmelCase				   =       AutoModel.from_pretrained("yjernite/retribert-base-uncased"     ).to("cuda:0"     )
										__lowerCAmelCase				   =       qar_model.eval()
					else:
										__lowerCAmelCase   ,							__lowerCAmelCase				   =       (None, None)
					if MODEL_TYPE == "bart":
										__lowerCAmelCase				   =       AutoTokenizer.from_pretrained("yjernite/bart_eli5"     )
										__lowerCAmelCase				   =       AutoModelForSeqaSeqLM.from_pretrained("yjernite/bart_eli5"     ).to("cuda:0"     )
										__lowerCAmelCase				   =       torch.load("seq2seq_models/eli5_bart_model_blm_2.pth"     )
										sas_model.load_state_dict(save_dict["model"]     )
										__lowerCAmelCase				   =       sas_model.eval()
					else:
										__lowerCAmelCase   ,							__lowerCAmelCase				   =       make_qa_sas_model(
										    model_name="t5-small"      ,      from_file="seq2seq_models/eli5_t5_model_1024_4.pth"      ,      device="cuda:0"     )
					return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)







@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_     )
def 	_a      (						):
					if LOAD_DENSE_INDEX:
										__lowerCAmelCase				   =       faiss.StandardGpuResources()
										__lowerCAmelCase				   =       datasets.load_dataset(path="wiki_snippets"      ,      name="wiki40b_en_100_0"     )["train"]
										__lowerCAmelCase				   =       np.memmap(
										    "wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"      ,      dtype="float32"      ,      mode="r"      ,      shape=(wikiaab_passages.num_rows, 1_28)      ,      )
										__lowerCAmelCase				   =       faiss.IndexFlatIP(1_28     )
										__lowerCAmelCase				   =       faiss.index_cpu_to_gpu(SCREAMING_SNAKE_CASE_      ,      1      ,      SCREAMING_SNAKE_CASE_     )
										wikiaab_gpu_index_flat.add(SCREAMING_SNAKE_CASE_     )  # TODO fix for larger GPU
					else:
										__lowerCAmelCase   ,							__lowerCAmelCase				   =       (None, None)
					__lowerCAmelCase				   =       Elasticsearch([{"host": "localhost", "port": "9200"}]     )
					return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)







@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_     )
def 	_a      (						):
					__lowerCAmelCase				   =       datasets.load_dataset("eli5"      ,      name="LFQA_reddit"     )
					__lowerCAmelCase				   =       elia["train_eli5"]
					__lowerCAmelCase				   =       np.memmap(
					    "eli5_questions_reps.dat"      ,      dtype="float32"      ,      mode="r"      ,      shape=(elia_train.num_rows, 1_28)     )
					__lowerCAmelCase				   =       faiss.IndexFlatIP(1_28     )
					eli5_train_q_index.add(SCREAMING_SNAKE_CASE_     )
					return (elia_train, eli5_train_q_index)


UpperCamelCase__			,	UpperCamelCase__			,	UpperCamelCase__    			=			load_indexes()
UpperCamelCase__			,	UpperCamelCase__			,	UpperCamelCase__			,	UpperCamelCase__    			=			load_models()
UpperCamelCase__			,	UpperCamelCase__    			=			load_train_data()







def 	_a      (						SCREAMING_SNAKE_CASE_							:				int      ,      SCREAMING_SNAKE_CASE_							:				Optional[int]=10     ):
					__lowerCAmelCase				   =       embed_questions_for_retrieval([question]      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_     )
					__lowerCAmelCase   ,							__lowerCAmelCase				   =       eli5_train_q_index.search(SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_     )
					__lowerCAmelCase				   =       [elia_train[int(SCREAMING_SNAKE_CASE_     )] for i in I[0]]
					return nn_examples







def 	_a      (						SCREAMING_SNAKE_CASE_							:				List[str]      ,      SCREAMING_SNAKE_CASE_							:				int="wiki40b"      ,      SCREAMING_SNAKE_CASE_							:				List[Any]="dense"      ,      SCREAMING_SNAKE_CASE_							:				int=10     ):
					if source == "none":
										__lowerCAmelCase   ,							__lowerCAmelCase				   =       (" <P> ".join(["" for _ in range(11     )]     ).strip(), [])
					else:
										if method == "dense":
															__lowerCAmelCase   ,							__lowerCAmelCase				   =       query_qa_dense_index(
															    SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_     )
										else:
															__lowerCAmelCase   ,							__lowerCAmelCase				   =       query_es_index(
															    SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      index_name="english_wiki40b_snippets_100w"      ,      n_results=SCREAMING_SNAKE_CASE_      ,      )
					__lowerCAmelCase				   =       [
					    (res["article_title"], res["section_title"].strip(), res["score"], res["passage_text"]) for res in hit_lst
					]
					__lowerCAmelCase				   =       "question: {} context: {}".format(SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_     )
					return question_doc, support_list







@st.cache(
    hash_funcs={
        torch.Tensor: (lambda SCREAMING_SNAKE_CASE_     : None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda SCREAMING_SNAKE_CASE_     : None),
    }     )
def 	_a      (						SCREAMING_SNAKE_CASE_							:				Any      ,      SCREAMING_SNAKE_CASE_							:				Optional[Any]      ,      SCREAMING_SNAKE_CASE_							:				Optional[int]      ,      SCREAMING_SNAKE_CASE_							:				Any=64      ,      SCREAMING_SNAKE_CASE_							:				Dict=2_56      ,      SCREAMING_SNAKE_CASE_							:				List[str]=False      ,      SCREAMING_SNAKE_CASE_							:				List[str]=2      ,      SCREAMING_SNAKE_CASE_							:				List[str]=0.95      ,      SCREAMING_SNAKE_CASE_							:				Union[str, Any]=0.8     ):
					with torch.no_grad():
										__lowerCAmelCase				   =       qa_sas_generate(
										    SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      SCREAMING_SNAKE_CASE_      ,      num_answers=1      ,      num_beams=SCREAMING_SNAKE_CASE_      ,      min_len=SCREAMING_SNAKE_CASE_      ,      max_len=SCREAMING_SNAKE_CASE_      ,      do_sample=SCREAMING_SNAKE_CASE_      ,      temp=SCREAMING_SNAKE_CASE_      ,      top_p=SCREAMING_SNAKE_CASE_      ,      top_k=SCREAMING_SNAKE_CASE_      ,      max_input_length=10_24      ,      device="cuda:0"      ,      )[0]
					return (answer, support_list)


st.title("""Long Form Question Answering with ELI5""")

# Start sidebar
UpperCamelCase__    			=			"""<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"""
UpperCamelCase__    			=			"""
<html>
  <head>
    <style>
      .img-container {
        padding-left: 90px;
        padding-right: 90px;
        padding-top: 50px;
        padding-bottom: 50px;
        background-color: #f0f3f9;
      }
    </style>
  </head>
  <body>
    <span class=\"img-container\"> <!-- Inline parent element -->
      %s
    </span>
  </body>
</html>
""" % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
UpperCamelCase__    			=			"""
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
"""
st.sidebar.markdown(description, unsafe_allow_html=True)

UpperCamelCase__    			=			[
    """Answer the question""",
    """View the retrieved document only""",
    """View the most similar ELI5 question and answer""",
    """Show me everything, please!""",
]
UpperCamelCase__    			=			st.sidebar.checkbox("""Demo options""")
if demo_options:
					UpperCamelCase__    			=			st.sidebar.selectbox(
					    """""",
					    action_list,
					    index=3,
					)
					UpperCamelCase__    			=			action_list.index(action_st)
					UpperCamelCase__    			=			st.sidebar.selectbox(
					    """""",
					    ["""Show full text of passages""", """Show passage section titles"""],
					    index=0,
					)
					UpperCamelCase__    			=			show_type == """Show full text of passages"""
else:
					UpperCamelCase__    			=			3
					UpperCamelCase__    			=			True

UpperCamelCase__    			=			st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
					UpperCamelCase__    			=			"""
    ### Information retriever options

    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
    """
					st.sidebar.markdown(retriever_info)
					UpperCamelCase__    			=			st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
					UpperCamelCase__    			=			st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
					UpperCamelCase__    			=			"""wiki40b"""
					UpperCamelCase__    			=			"""dense"""

UpperCamelCase__    			=			"""beam"""
UpperCamelCase__    			=			2
UpperCamelCase__    			=			64
UpperCamelCase__    			=			256
UpperCamelCase__    			=			None
UpperCamelCase__    			=			None
UpperCamelCase__    			=			st.sidebar.checkbox("""Generation options""")
if generate_options:
					UpperCamelCase__    			=			"""
    ### Answer generation options

    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
    **beam** search, or **sample** from the decoder's output probabilities.
    """
					st.sidebar.markdown(generate_info)
					UpperCamelCase__    			=			st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
					UpperCamelCase__    			=			st.sidebar.slider(
					    """Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None
					)
					UpperCamelCase__    			=			st.sidebar.slider(
					    """Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None
					)
					if sampled == "beam":
										UpperCamelCase__    			=			st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
					else:
										UpperCamelCase__    			=			st.sidebar.slider(
										    """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
										)
										UpperCamelCase__    			=			st.sidebar.slider(
										    """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
										)
										UpperCamelCase__    			=			None

# start main text
UpperCamelCase__    			=			[
    """<MY QUESTION>""",
    """How do people make chocolate?""",
    """Why do we get a fever when we are sick?""",
    """How can different animals perceive different colors?""",
    """What is natural language processing?""",
    """What's the best way to treat a sunburn?""",
    """What exactly are vitamins ?""",
    """How does nuclear energy provide electricity?""",
    """What's the difference between viruses and bacteria?""",
    """Why are flutes classified as woodwinds when most of them are made out of metal ?""",
    """Why do people like drinking coffee even though it tastes so bad?""",
    """What happens when wine ages? How does it make the wine taste better?""",
    """If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""",
    """How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""",
    """How does New Zealand have so many large bird predators?""",
]
UpperCamelCase__    			=			st.selectbox(
    """What would you like to ask? ---- select <MY QUESTION> to enter a new query""",
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
					UpperCamelCase__    			=			st.text_input("""Enter your question here:""", """""")
else:
					UpperCamelCase__    			=			question_s

if st.button("""Show me!"""):
					if action in [0, 1, 3]:
										if index_type == "mixed":
															UpperCamelCase__			,	UpperCamelCase__    			=			make_support(question, source=wiki_source, method="""dense""", n_results=10)
															UpperCamelCase__			,	UpperCamelCase__    			=			make_support(question, source=wiki_source, method="""sparse""", n_results=10)
															UpperCamelCase__    			=			[]
															for res_d, res_s in zip(support_list_dense, support_list_sparse):
																				if tuple(res_d) not in support_list:
																									support_list += [tuple(res_d)]
																				if tuple(res_s) not in support_list:
																									support_list += [tuple(res_s)]
															UpperCamelCase__    			=			support_list[:10]
															UpperCamelCase__    			=			"""<P> """ + """ <P> """.join([res[-1] for res in support_list])
										else:
															UpperCamelCase__			,	UpperCamelCase__    			=			make_support(question, source=wiki_source, method=index_type, n_results=10)
					if action in [0, 3]:
										UpperCamelCase__			,	UpperCamelCase__    			=			answer_question(
										    question_doc,
										    sas_model,
										    sas_tokenizer,
										    min_len=min_len,
										    max_len=int(max_len),
										    sampling=(sampled == """sampled"""),
										    n_beams=n_beams,
										    top_p=top_p,
										    temp=temp,
										)
										st.markdown("""### The model generated answer is:""")
										st.write(answer)
					if action in [0, 1, 3] and wiki_source != "none":
										st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""")
										for i, res in enumerate(support_list):
															UpperCamelCase__    			=			"""https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_"""))
															UpperCamelCase__    			=			res[1].strip()
															if sec_titles == "":
																				UpperCamelCase__    			=			"""[{}]({})""".format(res[0], wiki_url)
															else:
																				UpperCamelCase__    			=			sec_titles.split(""" & """)
																				UpperCamelCase__    			=			""" & """.join(
																				    ["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list]
																				)
															st.markdown(
															    """{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}""".format(i + 1, res[0], sections),
															    unsafe_allow_html=True,
															)
															if show_passages:
																				st.write(
																				    """> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True
																				)
					if action in [2, 3]:
										UpperCamelCase__    			=			find_nearest_training(question)
										UpperCamelCase__    			=			nn_train_list[0]
										st.markdown(
										    """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
										)
										UpperCamelCase__    			=			[
										    """{}. {}""".format(i + 1, """  \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""]))
										    for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""]))
										    if i == 0 or sc > 2
										]
										st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st)))


UpperCamelCase__    			=			"""
---

**Disclaimer**

*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
"""


st.sidebar.markdown(disclaimer, unsafe_allow_html=True)










import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class 			a__    (					snake_case__ ,				snake_case__ ,				snake_case__ ,				unittest.TestCase      ):
						_a							:    str					=    StableUnCLIPPipeline
						_a							:    Union[str, Any]					=    TEXT_TO_IMAGE_PARAMS
						_a							:    Dict					=    TEXT_TO_IMAGE_BATCH_PARAMS
						_a							:    Optional[int]					=    TEXT_TO_IMAGE_IMAGE_PARAMS
						_a							:    Dict					=    TEXT_TO_IMAGE_IMAGE_PARAMS

						# TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
						_a							:    Optional[Any]					=    False






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       3_2
											__lowerCAmelCase				   =       embedder_hidden_size

											# prior components

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       CLIPTextModelWithProjection(
											    CLIPTextConfig(
											        bos_token_id=0		,			eos_token_id=2		,			hidden_size=_A		,			projection_dim=_A		,			intermediate_size=3_7		,			layer_norm_eps=1E-0_5		,			num_attention_heads=4		,			num_hidden_layers=5		,			pad_token_id=1		,			vocab_size=1_0_0_0		,			)			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       PriorTransformer(
											    num_attention_heads=2		,			attention_head_dim=1_2		,			embedding_dim=_A		,			num_layers=1		,			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       DDPMScheduler(
											    variance_type="fixed_small_log"		,			prediction_type="sample"		,			num_train_timesteps=1_0_0_0		,			clip_sample=_A		,			clip_sample_range=5.0		,			beta_schedule="squaredcos_cap_v2"		,			)

											# regular denoising components

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       StableUnCLIPImageNormalizer(embedding_dim=_A			)
											__lowerCAmelCase				   =       DDPMScheduler(beta_schedule="squaredcos_cap_v2"			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       CLIPTextModel(
											    CLIPTextConfig(
											        bos_token_id=0		,			eos_token_id=2		,			hidden_size=_A		,			projection_dim=3_2		,			intermediate_size=3_7		,			layer_norm_eps=1E-0_5		,			num_attention_heads=4		,			num_hidden_layers=5		,			pad_token_id=1		,			vocab_size=1_0_0_0		,			)			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       UNetaDConditionModel(
											    sample_size=3_2		,			in_channels=4		,			out_channels=4		,			down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")		,			up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")		,			block_out_channels=(3_2, 6_4)		,			attention_head_dim=(2, 4)		,			class_embed_type="projection"		,			projection_class_embeddings_input_dim=embedder_projection_dim * 2		,			cross_attention_dim=_A		,			layers_per_block=1		,			upcast_attention=_A		,			use_linear_projection=_A		,			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       DDIMScheduler(
											    beta_schedule="scaled_linear"		,			beta_start=0.0_00_85		,			beta_end=0.0_12		,			prediction_type="v_prediction"		,			set_alpha_to_one=_A		,			steps_offset=1		,			)

											torch.manual_seed(0			)
											__lowerCAmelCase				   =       AutoencoderKL()

											__lowerCAmelCase				   =       {
											    # prior components
											    "prior_tokenizer": prior_tokenizer,
											    "prior_text_encoder": prior_text_encoder,
											    "prior": prior,
											    "prior_scheduler": prior_scheduler,
											    # image noising components
											    "image_normalizer": image_normalizer,
											    "image_noising_scheduler": image_noising_scheduler,
											    # regular denoising components
											    "tokenizer": tokenizer,
											    "text_encoder": text_encoder,
											    "unet": unet,
											    "scheduler": scheduler,
											    "vae": vae,
											}

											return components






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A		,			_A=0			):




											"""simple docstring"""



											if str(_A			).startswith("mps"			):
																__lowerCAmelCase				   =       torch.manual_seed(_A			)
											else:
																__lowerCAmelCase				   =       torch.Generator(device=_A			).manual_seed(_A			)
											__lowerCAmelCase				   =       {
											    "prompt": "A painting of a squirrel eating a burger",
											    "generator": generator,
											    "num_inference_steps": 2,
											    "prior_num_inference_steps": 2,
											    "output_type": "numpy",
											}
											return inputs






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       torch_device == "cpu"

											self._test_attention_slicing_forward_pass(test_max_difference=_A			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       torch_device in ["cpu", "mps"]

											self._test_inference_batch_single_identical(test_max_difference=_A			)






@slow
@require_torch_gpu
class 			a__    (					unittest.TestCase      ):






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       load_numpy(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy"			)

											__lowerCAmelCase				   =       StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"		,			torch_dtype=torch.floataa			)
											pipe.to(_A			)
											pipe.set_progress_bar_config(disable=_A			)
											# stable unclip will oom when integration tests are run on a V100,
											# so turn on memory savings
											pipe.enable_attention_slicing()
											pipe.enable_sequential_cpu_offload()

											__lowerCAmelCase				   =       torch.Generator(device="cpu"			).manual_seed(0			)
											__lowerCAmelCase				   =       pipe("anime turle"		,			generator=_A		,			output_type="np"			)

											__lowerCAmelCase				   =       output.images[0]

											assert image.shape == (7_6_8, 7_6_8, 3)

											assert_mean_pixel_difference(_A		,			_A			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											torch.cuda.empty_cache()
											torch.cuda.reset_max_memory_allocated()
											torch.cuda.reset_peak_memory_stats()

											__lowerCAmelCase				   =       StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"		,			torch_dtype=torch.floataa			)
											__lowerCAmelCase				   =       pipe.to(_A			)
											pipe.set_progress_bar_config(disable=_A			)
											pipe.enable_attention_slicing()
											pipe.enable_sequential_cpu_offload()

											__lowerCAmelCase				   =       pipe(
											    "anime turtle"		,			prior_num_inference_steps=2		,			num_inference_steps=2		,			output_type="np"		,			)

											__lowerCAmelCase				   =       torch.cuda.max_memory_allocated()
											# make sure that less than 7 GB is allocated
											assert mem_bytes < 7 * 1_0**9




