
'''simple docstring'''


import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


__SCREAMING_SNAKE_CASE						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE						=      [
    "yjernite/retribert-base-uncased",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]




class     __snake_case			(    _a	):
		a_          =					RetriBertConfig
		a_          =					None
		a_          =					"retribert"




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






								'''simple docstring'''






								if isinstance(_SCREAMING_SNAKE_CASE			,    nn.Linear):
														module.weight.data.normal_(mean=0.0			,    std=self.config.initializer_range)
														if module.bias is not None:
																				module.bias.data.zero_()
								elif isinstance(_SCREAMING_SNAKE_CASE			,    nn.Embedding):
														module.weight.data.normal_(mean=0.0			,    std=self.config.initializer_range)
														if module.padding_idx is not None:
																				module.weight.data[module.padding_idx].zero_()
								elif isinstance(_SCREAMING_SNAKE_CASE			,    nn.LayerNorm):
														module.bias.data.zero_()
														module.weight.data.fill_(1.0)







__SCREAMING_SNAKE_CASE						=      r"\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"




@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."					,			_a					,			)
class     __snake_case			(    _a	):




		def __init__(  self					:Optional[Any]			,    _SCREAMING_SNAKE_CASE					:RetriBertConfig)					->			None:






								'''simple docstring'''






								super().__init__(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	List[Any]					     =     config.projection_dim

								UpperCamelCase_     :	List[str]					     =     BertModel(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	Union[str, Any]					     =     None if config.share_encoders else BertModel(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	int					     =     nn.Dropout(config.hidden_dropout_prob)
								UpperCamelCase_     :	int					     =     nn.Linear(config.hidden_size			,    config.projection_dim			,    bias=_SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	Optional[Any]					     =     nn.Linear(config.hidden_size			,    config.projection_dim			,    bias=_SCREAMING_SNAKE_CASE)

								UpperCamelCase_     :	Any					     =     nn.CrossEntropyLoss(reduction="""mean""")

								# Initialize weights and apply final processing
								self.post_init()




		def 	_snake_case	(  self					:Optional[int]			,    _SCREAMING_SNAKE_CASE					:int			,    _SCREAMING_SNAKE_CASE					:Tuple			,    _SCREAMING_SNAKE_CASE					:Optional[int]			,    _SCREAMING_SNAKE_CASE					:List[Any]=-1			,    )					->			List[Any]:






								'''simple docstring'''






								if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
														return sent_encoder(_SCREAMING_SNAKE_CASE			,    attention_mask=_SCREAMING_SNAKE_CASE)[1]
								else:
														# prepare implicit variables
														UpperCamelCase_     :	Any					     =     input_ids.device
														UpperCamelCase_     :	str					     =     input_ids.size()
														UpperCamelCase_     :	Optional[Any]					     =     torch.zeros(_SCREAMING_SNAKE_CASE			,    dtype=torch.long			,    device=_SCREAMING_SNAKE_CASE)
														UpperCamelCase_     :	int					     =     [None] * sent_encoder.config.num_hidden_layers
														UpperCamelCase_     :	torch.Tensor					     =     sent_encoder.get_extended_attention_mask(
														    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)

														# define function for checkpointing
														def partial_encode(*_SCREAMING_SNAKE_CASE					:Optional[Any]):
																				UpperCamelCase_     :	List[Any]					     =     sent_encoder.encoder(
																				    inputs[0]			,    attention_mask=inputs[1]			,    head_mask=_SCREAMING_SNAKE_CASE			,    )
																				UpperCamelCase_     :	Optional[int]					     =     encoder_outputs[0]
																				UpperCamelCase_     :	Tuple					     =     sent_encoder.pooler(_SCREAMING_SNAKE_CASE)
																				return pooled_output

														# run embedding layer on everything at once
														UpperCamelCase_     :	Tuple					     =     sent_encoder.embeddings(
														    input_ids=_SCREAMING_SNAKE_CASE			,    position_ids=_SCREAMING_SNAKE_CASE			,    token_type_ids=_SCREAMING_SNAKE_CASE			,    inputs_embeds=_SCREAMING_SNAKE_CASE)
														# run encoding and pooling on one mini-batch at a time
														UpperCamelCase_     :	Optional[int]					     =     []
														for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
																				UpperCamelCase_     :	Dict					     =     embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																				UpperCamelCase_     :	Tuple					     =     extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																				UpperCamelCase_     :	List[Any]					     =     checkpoint.checkpoint(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)
																				pooled_output_list.append(_SCREAMING_SNAKE_CASE)
														return torch.cat(_SCREAMING_SNAKE_CASE			,    dim=0)




		def 	_snake_case	(  self					:List[str]			,    _SCREAMING_SNAKE_CASE					:str			,    _SCREAMING_SNAKE_CASE					:Tuple=None			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]=-1			,    )					->			List[str]:






								'''simple docstring'''






								UpperCamelCase_     :	Dict					     =     self.embed_sentences_checkpointed(
								    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    self.bert_query			,    _SCREAMING_SNAKE_CASE			,    )
								return self.project_query(_SCREAMING_SNAKE_CASE)




		def 	_snake_case	(  self					:str			,    _SCREAMING_SNAKE_CASE					:Dict			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]=None			,    _SCREAMING_SNAKE_CASE					:Tuple=-1			,    )					->			List[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Union[str, Any]					     =     self.embed_sentences_checkpointed(
								    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    self.bert_query if self.bert_doc is None else self.bert_doc			,    _SCREAMING_SNAKE_CASE			,    )
								return self.project_doc(_SCREAMING_SNAKE_CASE)





		def 	_snake_case	(  self					:Optional[Any]			,    _SCREAMING_SNAKE_CASE					:torch.LongTensor			,    _SCREAMING_SNAKE_CASE					:Optional[torch.FloatTensor]			,    _SCREAMING_SNAKE_CASE					:torch.LongTensor			,    _SCREAMING_SNAKE_CASE					:Optional[torch.FloatTensor]			,    _SCREAMING_SNAKE_CASE					:int = -1			,    )					->			torch.FloatTensor:






								'''simple docstring'''






								UpperCamelCase_     :	str					     =     input_ids_query.device
								UpperCamelCase_     :	Optional[int]					     =     self.embed_questions(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	List[str]					     =     self.embed_answers(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)
								UpperCamelCase_     :	Tuple					     =     torch.mm(_SCREAMING_SNAKE_CASE			,    a_reps.t())
								UpperCamelCase_     :	Tuple					     =     self.ce_loss(_SCREAMING_SNAKE_CASE			,    torch.arange(compare_scores.shape[1]).to(_SCREAMING_SNAKE_CASE))
								UpperCamelCase_     :	Optional[int]					     =     self.ce_loss(compare_scores.t()			,    torch.arange(compare_scores.shape[0]).to(_SCREAMING_SNAKE_CASE))
								UpperCamelCase_     :	str					     =     (loss_qa + loss_aq) / 2
								return loss






'''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


__SCREAMING_SNAKE_CASE						=      logging.get_logger(__name__)  # pylint: disable=invalid-name




class     __snake_case			(    _a	):
		a_          =					["safety_checker", "feature_extractor"]




		def __init__(  self					:str			,    _SCREAMING_SNAKE_CASE					:AutoencoderKL			,    _SCREAMING_SNAKE_CASE					:CLIPTextModel			,    _SCREAMING_SNAKE_CASE					:CLIPTokenizer			,    _SCREAMING_SNAKE_CASE					:UNetaDConditionModel			,    _SCREAMING_SNAKE_CASE					:Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]			,    _SCREAMING_SNAKE_CASE					:StableDiffusionSafetyChecker			,    _SCREAMING_SNAKE_CASE					:CLIPImageProcessor			,    _SCREAMING_SNAKE_CASE					:bool = True			,    )					->			int:






								'''simple docstring'''






								super().__init__()
								if hasattr(scheduler.config			,    """steps_offset""") and scheduler.config.steps_offset != 1:
														UpperCamelCase_     :	Optional[Any]					     =     (
														    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"""			,    _SCREAMING_SNAKE_CASE			,    standard_warn=_SCREAMING_SNAKE_CASE)
														UpperCamelCase_     :	Union[str, Any]					     =     dict(scheduler.config)
														UpperCamelCase_     :	Optional[Any]					     =     1
														UpperCamelCase_     :	int					     =     FrozenDict(_SCREAMING_SNAKE_CASE)

								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			,    )
								self.register_to_config(requires_safety_checker=_SCREAMING_SNAKE_CASE)




		@property
		def 	_snake_case	(  self					:Tuple)					->			Dict[str, Any]:






								'''simple docstring'''






								return {k: getattr(self			,    _SCREAMING_SNAKE_CASE) for k in self.config.keys() if not k.startswith("""_""")}




		def 	_snake_case	(  self					:Optional[int]			,    _SCREAMING_SNAKE_CASE					:Optional[Union[str, int]] = "auto")					->			Union[str, Any]:






								'''simple docstring'''






								if slice_size == "auto":
														# half the attention head size is usually a good trade-off between
														# speed and memory
														UpperCamelCase_     :	int					     =     self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE)




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






								'''simple docstring'''






								self.enable_attention_slicing(_SCREAMING_SNAKE_CASE)




		@torch.no_grad()
		def 	_snake_case	(  self					:Union[str, Any]			,    _SCREAMING_SNAKE_CASE					:Union[str, List[str]]			,    _SCREAMING_SNAKE_CASE					:Union[torch.FloatTensor, PIL.Image.Image]			,    _SCREAMING_SNAKE_CASE					:Union[torch.FloatTensor, PIL.Image.Image]			,    _SCREAMING_SNAKE_CASE					:float = 0.8			,    _SCREAMING_SNAKE_CASE					:Optional[int] = 5_0			,    _SCREAMING_SNAKE_CASE					:Optional[float] = 7.5			,    _SCREAMING_SNAKE_CASE					:Optional[Union[str, List[str]]] = None			,    _SCREAMING_SNAKE_CASE					:Optional[int] = 1			,    _SCREAMING_SNAKE_CASE					:Optional[float] = 0.0			,    _SCREAMING_SNAKE_CASE					:Optional[torch.Generator] = None			,    _SCREAMING_SNAKE_CASE					:Optional[str] = "pil"			,    _SCREAMING_SNAKE_CASE					:bool = True			,    _SCREAMING_SNAKE_CASE					:Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,    _SCREAMING_SNAKE_CASE					:int = 1			,    )					->			List[str]:






								'''simple docstring'''






								return StableDiffusionInpaintPipelineLegacy(**self.components)(
								    prompt=_SCREAMING_SNAKE_CASE			,    image=_SCREAMING_SNAKE_CASE			,    mask_image=_SCREAMING_SNAKE_CASE			,    strength=_SCREAMING_SNAKE_CASE			,    num_inference_steps=_SCREAMING_SNAKE_CASE			,    guidance_scale=_SCREAMING_SNAKE_CASE			,    negative_prompt=_SCREAMING_SNAKE_CASE			,    num_images_per_prompt=_SCREAMING_SNAKE_CASE			,    eta=_SCREAMING_SNAKE_CASE			,    generator=_SCREAMING_SNAKE_CASE			,    output_type=_SCREAMING_SNAKE_CASE			,    return_dict=_SCREAMING_SNAKE_CASE			,    callback=_SCREAMING_SNAKE_CASE			,    )




		@torch.no_grad()
		def 	_snake_case	(  self					:List[str]			,    _SCREAMING_SNAKE_CASE					:Union[str, List[str]]			,    _SCREAMING_SNAKE_CASE					:Union[torch.FloatTensor, PIL.Image.Image]			,    _SCREAMING_SNAKE_CASE					:float = 0.8			,    _SCREAMING_SNAKE_CASE					:Optional[int] = 5_0			,    _SCREAMING_SNAKE_CASE					:Optional[float] = 7.5			,    _SCREAMING_SNAKE_CASE					:Optional[Union[str, List[str]]] = None			,    _SCREAMING_SNAKE_CASE					:Optional[int] = 1			,    _SCREAMING_SNAKE_CASE					:Optional[float] = 0.0			,    _SCREAMING_SNAKE_CASE					:Optional[torch.Generator] = None			,    _SCREAMING_SNAKE_CASE					:Optional[str] = "pil"			,    _SCREAMING_SNAKE_CASE					:bool = True			,    _SCREAMING_SNAKE_CASE					:Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,    _SCREAMING_SNAKE_CASE					:int = 1			,    **_SCREAMING_SNAKE_CASE					:int			,    )					->			Any:






								'''simple docstring'''






								return StableDiffusionImgaImgPipeline(**self.components)(
								    prompt=_SCREAMING_SNAKE_CASE			,    image=_SCREAMING_SNAKE_CASE			,    strength=_SCREAMING_SNAKE_CASE			,    num_inference_steps=_SCREAMING_SNAKE_CASE			,    guidance_scale=_SCREAMING_SNAKE_CASE			,    negative_prompt=_SCREAMING_SNAKE_CASE			,    num_images_per_prompt=_SCREAMING_SNAKE_CASE			,    eta=_SCREAMING_SNAKE_CASE			,    generator=_SCREAMING_SNAKE_CASE			,    output_type=_SCREAMING_SNAKE_CASE			,    return_dict=_SCREAMING_SNAKE_CASE			,    callback=_SCREAMING_SNAKE_CASE			,    callback_steps=_SCREAMING_SNAKE_CASE			,    )





		@torch.no_grad()
		def 	_snake_case	(  self					:Any			,    _SCREAMING_SNAKE_CASE					:Union[str, List[str]]			,    _SCREAMING_SNAKE_CASE					:int = 5_1_2			,    _SCREAMING_SNAKE_CASE					:int = 5_1_2			,    _SCREAMING_SNAKE_CASE					:int = 5_0			,    _SCREAMING_SNAKE_CASE					:float = 7.5			,    _SCREAMING_SNAKE_CASE					:Optional[Union[str, List[str]]] = None			,    _SCREAMING_SNAKE_CASE					:Optional[int] = 1			,    _SCREAMING_SNAKE_CASE					:float = 0.0			,    _SCREAMING_SNAKE_CASE					:Optional[torch.Generator] = None			,    _SCREAMING_SNAKE_CASE					:Optional[torch.FloatTensor] = None			,    _SCREAMING_SNAKE_CASE					:Optional[str] = "pil"			,    _SCREAMING_SNAKE_CASE					:bool = True			,    _SCREAMING_SNAKE_CASE					:Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,    _SCREAMING_SNAKE_CASE					:int = 1			,    )					->			List[Any]:






								'''simple docstring'''






								return StableDiffusionPipeline(**self.components)(
								    prompt=_SCREAMING_SNAKE_CASE			,    height=_SCREAMING_SNAKE_CASE			,    width=_SCREAMING_SNAKE_CASE			,    num_inference_steps=_SCREAMING_SNAKE_CASE			,    guidance_scale=_SCREAMING_SNAKE_CASE			,    negative_prompt=_SCREAMING_SNAKE_CASE			,    num_images_per_prompt=_SCREAMING_SNAKE_CASE			,    eta=_SCREAMING_SNAKE_CASE			,    generator=_SCREAMING_SNAKE_CASE			,    latents=_SCREAMING_SNAKE_CASE			,    output_type=_SCREAMING_SNAKE_CASE			,    return_dict=_SCREAMING_SNAKE_CASE			,    callback=_SCREAMING_SNAKE_CASE			,    callback_steps=_SCREAMING_SNAKE_CASE			,    )




