




'''simple docstring'''




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()

class 						lowerCAmelCase_   ( lowerCamelCase_			,  unittest.TestCase   ):







  '''simple docstring'''







  lowerCAmelCase_				:					Tuple				     =						KandinskyPipeline
  lowerCAmelCase_				:					Union[str, Any]				     =						[
      """prompt""",
      """image_embeds""",
      """negative_image_embeds""",
  ]
  lowerCAmelCase_				:					Optional[Any]				     =						["""prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds"""]
  lowerCAmelCase_				:					List[Any]				     =						[
      """generator""",
      """height""",
      """width""",
      """latents""",
      """guidance_scale""",
      """negative_prompt""",
      """num_inference_steps""",
      """return_dict""",
      """guidance_scale""",
      """num_images_per_prompt""",
      """output_type""",
      """return_dict""",
  ]
  lowerCAmelCase_				:					int				     =						False


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	int ):






   """simple docstring"""






   return 32


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Dict ):






   """simple docstring"""






   return 32


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	List[Any] ):






   """simple docstring"""






   return self.time_input_dim


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int] ):






   """simple docstring"""






   return self.time_input_dim * 4


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Dict ):






   """simple docstring"""






   return 1_00


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	str ):






   """simple docstring"""






   UpperCAmelCase__										=    XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" )
   return tokenizer


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	str ):






   """simple docstring"""






   torch.manual_seed(0 )
   UpperCAmelCase__										=    MCLIPConfig(
       numDims=self.cross_attention_dim						,		transformerDimensions=self.text_embedder_hidden_size						,		hidden_size=self.text_embedder_hidden_size						,		intermediate_size=37						,		num_attention_heads=4						,		num_hidden_layers=5						,		vocab_size=10_05						,		)

   UpperCAmelCase__										=    MultilingualCLIP(_UpperCAmelCase )
   UpperCAmelCase__										=    text_encoder.eval()

   return text_encoder


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	int ):






   """simple docstring"""






   torch.manual_seed(0 )

   UpperCAmelCase__										=    {
       """in_channels""": 4,
       # Out channels is double in channels because predicts mean and variance
       """out_channels""": 8,
       """addition_embed_type""": """text_image""",
       """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
       """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
       """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
       """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
       """layers_per_block""": 1,
       """encoder_hid_dim""": self.text_embedder_hidden_size,
       """encoder_hid_dim_type""": """text_image_proj""",
       """cross_attention_dim""": self.cross_attention_dim,
       """attention_head_dim""": 4,
       """resnet_time_scale_shift""": """scale_shift""",
       """class_embed_type""": None,
   }

   UpperCAmelCase__										=    UNetaDConditionModel(**_UpperCAmelCase )
   return model


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any ):






   """simple docstring"""






   return {
       "block_out_channels": [32, 64],
       "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
       "in_channels": 3,
       "latent_channels": 4,
       "layers_per_block": 1,
       "norm_num_groups": 8,
       "norm_type": "spatial",
       "num_vq_embeddings": 12,
       "out_channels": 3,
       "up_block_types": [
           "AttnUpDecoderBlock2D",
           "UpDecoderBlock2D",
       ],
       "vq_embed_dim": 4,
   }


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	str ):






   """simple docstring"""






   torch.manual_seed(0 )
   UpperCAmelCase__										=    VQModel(**self.dummy_movq_kwargs )
   return model


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[Any] ):






   """simple docstring"""






   UpperCAmelCase__										=    self.dummy_text_encoder
   UpperCAmelCase__										=    self.dummy_tokenizer
   UpperCAmelCase__										=    self.dummy_unet
   UpperCAmelCase__										=    self.dummy_movq

   UpperCAmelCase__										=    DDIMScheduler(
       num_train_timesteps=10_00						,		beta_schedule="""linear"""						,		beta_start=0.0_0085						,		beta_end=0.012						,		clip_sample=_UpperCAmelCase						,		set_alpha_to_one=_UpperCAmelCase						,		steps_offset=1						,		prediction_type="""epsilon"""						,		thresholding=_UpperCAmelCase						,		)

   UpperCAmelCase__										=    {
       """text_encoder""": text_encoder,
       """tokenizer""": tokenizer,
       """unet""": unet,
       """scheduler""": scheduler,
       """movq""": movq,
   }
   return components


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[Any]						,		_UpperCAmelCase    :	Tuple						,		_UpperCAmelCase    :	Tuple=0 ):






   """simple docstring"""






   UpperCAmelCase__										=    floats_tensor((1, self.cross_attention_dim)						,		rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase )
   UpperCAmelCase__										=    floats_tensor((1, self.cross_attention_dim)						,		rng=random.Random(seed + 1 ) ).to(_UpperCAmelCase )
   if str(_UpperCAmelCase ).startswith("""mps""" ):
    UpperCAmelCase__										=    torch.manual_seed(_UpperCAmelCase )
   else:
    UpperCAmelCase__										=    torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase )
   UpperCAmelCase__										=    {
       """prompt""": """horse""",
       """image_embeds""": image_embeds,
       """negative_image_embeds""": negative_image_embeds,
       """generator""": generator,
       """height""": 64,
       """width""": 64,
       """guidance_scale""": 4.0,
       """num_inference_steps""": 2,
       """output_type""": """np""",
   }
   return inputs



  def 							SCREAMING_SNAKE_CASE__			(						self    :	int ):






   """simple docstring"""






   UpperCAmelCase__										=    """cpu"""

   UpperCAmelCase__										=    self.get_dummy_components()

   UpperCAmelCase__										=    self.pipeline_class(**_UpperCAmelCase )
   UpperCAmelCase__										=    pipe.to(_UpperCAmelCase )

   pipe.set_progress_bar_config(disable=_UpperCAmelCase )

   UpperCAmelCase__										=    pipe(**self.get_dummy_inputs(_UpperCAmelCase ) )
   UpperCAmelCase__										=    output.images

   UpperCAmelCase__										=    pipe(
       **self.get_dummy_inputs(_UpperCAmelCase )						,		return_dict=_UpperCAmelCase						,		)[0]

   UpperCAmelCase__										=    image[0, -3:, -3:, -1]
   UpperCAmelCase__										=    image_from_tuple[0, -3:, -3:, -1]

   assert image.shape == (1, 64, 64, 3)

   UpperCAmelCase__										=    np.array(
       [0.32_8663, 1.0, 0.2321_6873, 1.0, 0.9271_7564, 0.463_9046, 0.9689_4777, 0.3171_3378, 0.629_3953] )

   assert (
       np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
   ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
   assert (
       np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
   ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''

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







  '''simple docstring'''







  def 							SCREAMING_SNAKE_CASE__			(						self    :	int ):






   """simple docstring"""






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



  def 							SCREAMING_SNAKE_CASE__			(						self    :	List[str] ):






   """simple docstring"""






   UpperCAmelCase__										=    load_numpy(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
       """/kandinsky/kandinsky_text2img_cat_fp16.npy""" )

   UpperCAmelCase__										=    KandinskyPriorPipeline.from_pretrained(
       """kandinsky-community/kandinsky-2-1-prior"""						,		torch_dtype=torch.floataa )
   pipe_prior.to(_UpperCAmelCase )

   UpperCAmelCase__										=    KandinskyPipeline.from_pretrained("""kandinsky-community/kandinsky-2-1"""						,		torch_dtype=torch.floataa )
   UpperCAmelCase__										=    pipeline.to(_UpperCAmelCase )
   pipeline.set_progress_bar_config(disable=_UpperCAmelCase )

   UpperCAmelCase__										=    """red cat, 4k photo"""

   UpperCAmelCase__										=    torch.Generator(device="""cuda""" ).manual_seed(0 )
   UpperCAmelCase__							,			UpperCAmelCase__										=    pipe_prior(
       _UpperCAmelCase						,		generator=_UpperCAmelCase						,		num_inference_steps=5						,		negative_prompt=""""""						,		).to_tuple()

   UpperCAmelCase__										=    torch.Generator(device="""cuda""" ).manual_seed(0 )
   UpperCAmelCase__										=    pipeline(
       _UpperCAmelCase						,		image_embeds=_UpperCAmelCase						,		negative_image_embeds=_UpperCAmelCase						,		generator=_UpperCAmelCase						,		num_inference_steps=1_00						,		output_type="""np"""						,		)

   UpperCAmelCase__										=    output.images[0]

   assert image.shape == (5_12, 5_12, 3)

   assert_mean_pixel_difference(_UpperCAmelCase						,		_UpperCAmelCase )






'''simple docstring'''




import logging
import random

import ray

from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex


UpperCAmelCase_       				=      logging.getLogger(__name__)

class 						lowerCAmelCase_   :







  '''simple docstring'''







  def __init__(						self    :	int ):






   """simple docstring"""






   UpperCAmelCase__										=    False


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any						,		_UpperCAmelCase    :	Optional[Any]						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Tuple						,		_UpperCAmelCase    :	Optional[Any] ):






   """simple docstring"""






   if not self.initialized:
    UpperCAmelCase__										=    RagRetriever(
        _UpperCAmelCase						,		question_encoder_tokenizer=_UpperCAmelCase						,		generator_tokenizer=_UpperCAmelCase						,		index=_UpperCAmelCase						,		init_retrieval=_UpperCAmelCase						,		)
    UpperCAmelCase__										=    True


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






   """simple docstring"""






   self.retriever.index.init_index()


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






   """simple docstring"""






   del self.retriever
   UpperCAmelCase__										=    False



  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any						,		_UpperCAmelCase    :	Union[str, Any]						,		_UpperCAmelCase    :	Optional[int] ):






   """simple docstring"""






   UpperCAmelCase__							,			UpperCAmelCase__										=    self.retriever._main_retrieve(_UpperCAmelCase						,		_UpperCAmelCase )
   UpperCAmelCase__										=    self.retriever.index.get_doc_dicts(_UpperCAmelCase )
   return doc_ids, retrieved_doc_embeds, doc_dicts

class 						lowerCAmelCase_   ( lowerCamelCase_   ):







  '''simple docstring'''







  def __init__(						self    :	Optional[Any]						,		_UpperCAmelCase    :	List[Any]						,		_UpperCAmelCase    :	Dict						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Any						,		_UpperCAmelCase    :	List[Any]=None ):






   """simple docstring"""






   if index is not None and index.is_initialized() and len(_UpperCAmelCase ) > 0:
    raise ValueError(
        """When using Ray for distributed fine-tuning, """
        """you'll need to provide the paths instead, """
        """as the dataset and the index are loaded """
        """separately. More info in examples/rag/use_own_knowledge_dataset.py """ )

   super().__init__(
       _UpperCAmelCase						,		question_encoder_tokenizer=_UpperCAmelCase						,		generator_tokenizer=_UpperCAmelCase						,		index=_UpperCAmelCase						,		init_retrieval=_UpperCAmelCase						,		)

   UpperCAmelCase__										=    retrieval_workers
   UpperCAmelCase__										=    question_encoder_tokenizer
   UpperCAmelCase__										=    generator_tokenizer
   if len(self.retrieval_workers ) > 0:
    ray.get(
        [
            worker.create_rag_retriever.remote(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase )
            for worker in self.retrieval_workers
        ] )


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int] ):






   """simple docstring"""






   logger.info("""initializing retrieval""" )

   if len(self.retrieval_workers ) > 0:
    ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] )
   else:
    # Non-distributed training. Load index into this same process.
    self.index.init_index()


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Tuple						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Dict ):






   """simple docstring"""






   if len(self.retrieval_workers ) > 0:
    # Select a random retrieval actor.
    UpperCAmelCase__										=    self.retrieval_workers[random.randint(0						,		len(self.retrieval_workers ) - 1 )]
    UpperCAmelCase__							,			UpperCAmelCase__							,			UpperCAmelCase__										=    ray.get(
        random_worker.retrieve.remote(_UpperCAmelCase						,		_UpperCAmelCase ) )
   else:
    UpperCAmelCase__							,			UpperCAmelCase__										=    self._main_retrieve(_UpperCAmelCase						,		_UpperCAmelCase )
    UpperCAmelCase__										=    self.index.get_doc_dicts(_UpperCAmelCase )
   return retrieved_doc_embeds, doc_ids, doc_dicts


  @classmethod
  def 							SCREAMING_SNAKE_CASE__			(						cls    :	str						,		_UpperCAmelCase    :	Optional[Any]						,		_UpperCAmelCase    :	str=None						,		**_UpperCAmelCase    :	Tuple ):






   """simple docstring"""






   return super(_UpperCAmelCase						,		cls ).get_tokenizers(_UpperCAmelCase						,		_UpperCAmelCase						,		**_UpperCAmelCase )


  @classmethod
  def 							SCREAMING_SNAKE_CASE__			(						cls    :	int						,		_UpperCAmelCase    :	Optional[int]						,		_UpperCAmelCase    :	Optional[int]						,		_UpperCAmelCase    :	Union[str, Any]=None						,		**_UpperCAmelCase    :	int ):






   """simple docstring"""






   UpperCAmelCase__										=    kwargs.pop("""config"""						,		_UpperCAmelCase ) or RagConfig.from_pretrained(_UpperCAmelCase						,		**_UpperCAmelCase )
   UpperCAmelCase__										=    RagTokenizer.from_pretrained(_UpperCAmelCase						,		config=_UpperCAmelCase )
   UpperCAmelCase__										=    rag_tokenizer.question_encoder
   UpperCAmelCase__										=    rag_tokenizer.generator

   if indexed_dataset is not None:
    UpperCAmelCase__										=    """custom"""
    UpperCAmelCase__										=    CustomHFIndex(config.retrieval_vector_size						,		_UpperCAmelCase )
   else:
    UpperCAmelCase__										=    cls._build_index(_UpperCAmelCase )

   return cls(
       _UpperCAmelCase						,		question_encoder_tokenizer=_UpperCAmelCase						,		generator_tokenizer=_UpperCAmelCase						,		retrieval_workers=_UpperCAmelCase						,		index=_UpperCAmelCase						,		)



  def 							SCREAMING_SNAKE_CASE__			(						self    :	Dict ):






   """simple docstring"""






   logger.info("""re-loading the new dataset with embeddings""" )
   # access from the training loop

   ray.get([worker.clear_object.remote() for worker in self.retrieval_workers] )

   # build the index object again
   UpperCAmelCase__										=    self._build_index(self.config )

   ray.get(
       [
           worker.create_rag_retriever.remote(
               self.config						,		self.question_encoder_tokenizer						,		self.generator_tokenizer						,		_UpperCAmelCase )
           for worker in self.retrieval_workers
       ] )
