




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


__lowerCamelCase :    Tuple      						=      logging.get_logger(__name__)

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


class  lowerCamelCase     (		lowerCamelCase__    ):






			'''simple docstring'''





			UpperCamelCase__										=RetriBertConfig
			UpperCamelCase__										=None
			UpperCamelCase__										='''retribert'''

			def 				UpperCAmelCase__							(			self      : Dict							,    lowerCamelCase_      : Dict	)    -> Optional[int]:
								if isinstance(__UpperCamelCase							,    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(__UpperCamelCase							,    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(__UpperCamelCase							,    nn.LayerNorm	):
													module.bias.data.zero_()
													module.weight.data.fill_(1.0	)






__lowerCamelCase :    Optional[int]      						=      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.'''					,lowerCamelCase__					,)
class  lowerCamelCase     (		lowerCamelCase__    ):






			'''simple docstring'''





			def __init__(			self      : Optional[int]							,    lowerCamelCase_      : Tuple	)    -> None:
								super().__init__(__UpperCamelCase	)
								__magic_name__				:						str     				=				config.projection_dim

								__magic_name__				:						Optional[Any]     				=				BertModel(__UpperCamelCase	)
								__magic_name__				:						Dict     				=				None if config.share_encoders else BertModel(__UpperCamelCase	)
								__magic_name__				:						Optional[Any]     				=				nn.Dropout(config.hidden_dropout_prob	)
								__magic_name__				:						str     				=				nn.Linear(config.hidden_size							,    config.projection_dim							,    bias=__UpperCamelCase	)
								__magic_name__				:						Union[str, Any]     				=				nn.Linear(config.hidden_size							,    config.projection_dim							,    bias=__UpperCamelCase	)

								__magic_name__				:						Union[str, Any]     				=				nn.CrossEntropyLoss(reduction='''mean'''	)

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

			def 				UpperCAmelCase__							(			self      : Union[str, Any]							,    lowerCamelCase_      : Dict							,    lowerCamelCase_      : Optional[int]							,    lowerCamelCase_      : Dict							,    lowerCamelCase_      : str=-1							,    )    -> List[Any]:
								# reproduces BERT forward pass with checkpointing
								if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
													return sent_encoder(__UpperCamelCase							,    attention_mask=__UpperCamelCase	)[1]
								else:
													# prepare implicit variables
													__magic_name__				:						Any     				=				input_ids.device
													__magic_name__				:						Union[str, Any]     				=				input_ids.size()
													__magic_name__				:						Union[str, Any]     				=				torch.zeros(__UpperCamelCase							,    dtype=torch.long							,    device=__UpperCamelCase	)
													__magic_name__				:						Optional[Any]     				=				[None] * sent_encoder.config.num_hidden_layers
													__magic_name__				:						int     				=				sent_encoder.get_extended_attention_mask(
													    __UpperCamelCase							,    __UpperCamelCase	)

													# define function for checkpointing
													def partial_encode(*lowerCamelCase_      : Dict	):
																		__magic_name__				:						Dict     				=				sent_encoder.encoder(
																		    inputs[0]							,    attention_mask=inputs[1]							,    head_mask=__UpperCamelCase							,    )
																		__magic_name__				:						List[Any]     				=				encoder_outputs[0]
																		__magic_name__				:						List[Any]     				=				sent_encoder.pooler(__UpperCamelCase	)
																		return pooled_output

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

			def 				UpperCAmelCase__							(			self      : Tuple							,    lowerCamelCase_      : Tuple							,    lowerCamelCase_      : Dict=None							,    lowerCamelCase_      : List[Any]=-1							,    )    -> Optional[Any]:
								__magic_name__				:						Optional[Any]     				=				self.embed_sentences_checkpointed(
								    __UpperCamelCase							,    __UpperCamelCase							,    self.bert_query							,    __UpperCamelCase							,    )
								return self.project_query(__UpperCamelCase	)

			def 				UpperCAmelCase__							(			self      : List[str]							,    lowerCamelCase_      : Optional[int]							,    lowerCamelCase_      : int=None							,    lowerCamelCase_      : Union[str, Any]=-1							,    )    -> Optional[Any]:
								__magic_name__				:						List[Any]     				=				self.embed_sentences_checkpointed(
								    __UpperCamelCase							,    __UpperCamelCase							,    self.bert_query if self.bert_doc is None else self.bert_doc							,    __UpperCamelCase							,    )
								return self.project_doc(__UpperCamelCase	)


			def 				UpperCAmelCase__							(			self      : str							,    lowerCamelCase_      : Union[str, Any]							,    lowerCamelCase_      : str							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : List[Any]							,    lowerCamelCase_      : Optional[int] = -1							,    )    -> torch.FloatTensor:
								__magic_name__				:						Any     				=				input_ids_query.device
								__magic_name__				:						Optional[int]     				=				self.embed_questions(__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase	)
								__magic_name__				:						List[str]     				=				self.embed_answers(__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase	)
								__magic_name__				:						str     				=				torch.mm(__UpperCamelCase							,    a_reps.t()	)
								__magic_name__				:						List[str]     				=				self.ce_loss(__UpperCamelCase							,    torch.arange(compare_scores.shape[1]	).to(__UpperCamelCase	)	)
								__magic_name__				:						int     				=				self.ce_loss(compare_scores.t()							,    torch.arange(compare_scores.shape[0]	).to(__UpperCamelCase	)	)
								__magic_name__				:						Optional[int]     				=				(loss_qa + loss_aq) / 2
								return loss







'''simple docstring'''

import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowercase__					  =		False





@nightly
@require_torch_gpu
class     __SCREAMING_SNAKE_CASE       (   unittest.TestCase			):






     def 			a_       (      self		)							->     Union[str, Any]:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






     def 			a_       (      self		)							->     Dict:
          _a            =		VersatileDiffusionDualGuidedPipeline.from_pretrained("shi-labs/versatile-diffusion"		)
          # remove text_unet
          pipe.remove_unused_weights()
          pipe.to(__UpperCamelCase		)
          pipe.set_progress_bar_config(disable=__UpperCamelCase		)

          _a            =		load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)

          _a            =		torch.manual_seed(0		)
          _a            =		pipe(
              prompt="first prompt"  ,				image=__UpperCamelCase  ,				text_to_image_strength=0.75  ,				generator=__UpperCamelCase  ,				guidance_scale=7.5  ,				num_inference_steps=2  ,				output_type="numpy"  ,				).images

          with tempfile.TemporaryDirectory() as tmpdirname:
               pipe.save_pretrained(__UpperCamelCase		)
               _a            =		VersatileDiffusionDualGuidedPipeline.from_pretrained(__UpperCamelCase		)

          pipe.to(__UpperCamelCase		)
          pipe.set_progress_bar_config(disable=__UpperCamelCase		)

          _a            =		generator.manual_seed(0		)
          _a            =		pipe(
              prompt="first prompt"  ,				image=__UpperCamelCase  ,				text_to_image_strength=0.75  ,				generator=__UpperCamelCase  ,				guidance_scale=7.5  ,				num_inference_steps=2  ,				output_type="numpy"  ,				).images

          assert np.abs(image - new_image		).sum() < 1e-5, "Models don't have the same forward pass"






     def 			a_       (      self		)							->     int:
          _a            =		VersatileDiffusionDualGuidedPipeline.from_pretrained("shi-labs/versatile-diffusion"		)
          pipe.remove_unused_weights()
          pipe.to(__UpperCamelCase		)
          pipe.set_progress_bar_config(disable=__UpperCamelCase		)

          _a            =		"cyberpunk 2077"
          _a            =		load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)
          _a            =		torch.manual_seed(0		)
          _a            =		pipe(
              prompt=__UpperCamelCase  ,				image=__UpperCamelCase  ,				text_to_image_strength=0.75  ,				generator=__UpperCamelCase  ,				guidance_scale=7.5  ,				num_inference_steps=50  ,				output_type="numpy"  ,				).images

          _a            =		image[0, 253:256, 253:256, -1]

          assert image.shape == (1, 512, 512, 3)
          _a            =		np.array([0.07_87, 0.08_49, 0.08_26, 0.08_12, 0.08_07, 0.07_95, 0.08_18, 0.07_98, 0.07_79]		)

          assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-2

