




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					:     str					  =  logging.get_logger(__name__)

_lowerCamelCase					:     Optional[int]					  =  [
    "yjernite/retribert-base-uncased",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]
class 				__snake_case     (_a						):
				lowerCAmelCase__			=   RetriBertConfig
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   "retribert"



				def 					SCREAMING_SNAKE_CASE				(					self					:						Tuple						,		_UpperCAmelCase					:						Dict					)     ->			List[Any]:





								'''simple docstring'''




								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					:     str					  =  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					:						int						,		_UpperCAmelCase					:						RetriBertConfig					)     ->			None:





								'''simple docstring'''




								super().__init__(_UpperCAmelCase					)
								_lowerCAmelCase			:			str        =					config.projection_dim

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

								_lowerCAmelCase			:			List[Any]        =					nn.CrossEntropyLoss(reduction="""mean"""					)

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



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						Any						,		_UpperCAmelCase					:						Tuple						,		_UpperCAmelCase					:						List[Any]						,		_UpperCAmelCase					:						List[str]=-1						,		)     ->			Union[str, Any]:





								'''simple docstring'''




								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
												_lowerCAmelCase			:			List[Any]        =					input_ids.device
												_lowerCAmelCase			:			Optional[int]        =					input_ids.size()
												_lowerCAmelCase			:			Optional[Any]        =					torch.zeros(_UpperCAmelCase						,		dtype=torch.long						,		device=_UpperCAmelCase					)
												_lowerCAmelCase			:			List[str]        =					[None] * sent_encoder.config.num_hidden_layers
												_lowerCAmelCase			:			torch.Tensor        =					sent_encoder.get_extended_attention_mask(
												    _UpperCAmelCase						,		_UpperCAmelCase					)

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

												# run embedding layer on everything at once
												_lowerCAmelCase			:			List[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
												_lowerCAmelCase			:			Union[str, Any]        =					[]
												for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size					)					):
																_lowerCAmelCase			:			Any        =					embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																_lowerCAmelCase			:			int        =					extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																_lowerCAmelCase			:			Optional[Any]        =					checkpoint.checkpoint(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					)
																pooled_output_list.append(_UpperCAmelCase					)
												return torch.cat(_UpperCAmelCase						,		dim=0					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Union[str, Any]						,		_UpperCAmelCase					:						Union[str, Any]						,		_UpperCAmelCase					:						Tuple=None						,		_UpperCAmelCase					:						Any=-1						,		)     ->			Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Any        =					self.embed_sentences_checkpointed(
								    _UpperCAmelCase						,		_UpperCAmelCase						,		self.bert_query						,		_UpperCAmelCase						,		)
								return self.project_query(_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						str						,		_UpperCAmelCase					:						Optional[Any]						,		_UpperCAmelCase					:						List[str]=None						,		_UpperCAmelCase					:						Dict=-1						,		)     ->			Dict:





								'''simple docstring'''




								_lowerCAmelCase			:			Optional[int]        =					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 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						torch.LongTensor						,		_UpperCAmelCase					:						Optional[torch.FloatTensor]						,		_UpperCAmelCase					:						torch.LongTensor						,		_UpperCAmelCase					:						Optional[torch.FloatTensor]						,		_UpperCAmelCase					:						int = -1						,		)     ->			torch.FloatTensor:





								'''simple docstring'''




								_lowerCAmelCase			:			List[Any]        =					input_ids_query.device
								_lowerCAmelCase			:			str        =					self.embed_questions(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					)
								_lowerCAmelCase			:			List[str]        =					self.embed_answers(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					)
								_lowerCAmelCase			:			List[Any]        =					torch.mm(_UpperCAmelCase						,		a_reps.t()					)
								_lowerCAmelCase			:			Dict        =					self.ce_loss(_UpperCAmelCase						,		torch.arange(compare_scores.shape[1]					).to(_UpperCAmelCase					)					)
								_lowerCAmelCase			:			List[Any]        =					self.ce_loss(compare_scores.t()						,		torch.arange(compare_scores.shape[0]					).to(_UpperCAmelCase					)					)
								_lowerCAmelCase			:			Union[str, Any]        =					(loss_qa + loss_aq) / 2
								return loss







import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()
class 				__snake_case     (unittest.TestCase						):
				lowerCAmelCase__			=   "hf-internal-testing/tiny-stable-diffusion-pipe"
				lowerCAmelCase__			=   1
				lowerCAmelCase__			=   7_7
				lowerCAmelCase__			=   3_2
				lowerCAmelCase__			=   4
				lowerCAmelCase__			=   lowerCAmelCase__			=   6_4
				lowerCAmelCase__			=   torch.manual_seed(0						)



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[str]						,		_UpperCAmelCase					:						Optional[Any]=0.9999					)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			List[Any]        =					UNetaDConditionModel.from_pretrained(self.model_id						,		subfolder="""unet"""					)
								_lowerCAmelCase			:			Optional[Any]        =					unet.to(_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					EMAModel(unet.parameters()						,		decay=_UpperCAmelCase						,		model_cls=_UpperCAmelCase						,		model_config=unet.config					)
								return unet, ema_unet



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			Optional[int]:





								'''simple docstring'''




								_lowerCAmelCase			:			Any        =					torch.randn(
								    self.batch_size						,		self.num_in_channels						,		self.latent_height						,		self.latent_width						,		generator=self.generator					).to(_UpperCAmelCase					)
								_lowerCAmelCase			:			List[str]        =					torch.randint(0						,		1000						,		size=(self.batch_size,)						,		generator=self.generator					).to(_UpperCAmelCase					)
								_lowerCAmelCase			:			Any        =					torch.randn(
								    self.batch_size						,		self.prompt_length						,		self.text_encoder_hidden_dim						,		generator=self.generator					).to(_UpperCAmelCase					)
								return noisy_latents, timesteps, encoder_hidden_states



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						Dict					)     ->			Dict:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					{}
								for k, param in unet.state_dict().items():
												_lowerCAmelCase			:			List[Any]        =					torch.randn_like(_UpperCAmelCase					) + (param * torch.randn_like(_UpperCAmelCase					))
												updated_state_dict.update({k: updated_param}					)
								unet.load_state_dict(_UpperCAmelCase					)
								return unet



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[Any]					)     ->			Tuple:





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			Optional[int]        =					self.get_models()
								# Take the first (hypothetical) EMA step.
								ema_unet.step(unet.parameters()					)
								assert ema_unet.optimization_step == 1

								# Take two more.
								for _ in range(2					):
												ema_unet.step(unet.parameters()					)
								assert ema_unet.optimization_step == 3



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]					)     ->			str:





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			List[Any]        =					self.get_models()
								# Since the `unet` is not being updated (i.e., backprop'd)
								# there won't be any difference between the `params` of `unet`
								# and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
								ema_unet.step(unet.parameters()					)
								_lowerCAmelCase			:			Optional[int]        =					list(unet.parameters()					)
								for s_param, param in zip(ema_unet.shadow_params						,		_UpperCAmelCase					):
												assert torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)

								# The above holds true even if we call `ema.step()` multiple times since
								# `unet` params are still not being updated.
								for _ in range(4					):
												ema_unet.step(unet.parameters()					)
								for s_param, param in zip(ema_unet.shadow_params						,		_UpperCAmelCase					):
												assert torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)



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





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			Union[str, Any]        =					self.get_models()
								# Here we simulate the parameter updates for `unet`. Since there might
								# be some parameters which are initialized to zero we take extra care to
								# initialize their values to something non-zero before the multiplication.
								_lowerCAmelCase			:			str        =					self.simulate_backprop(_UpperCAmelCase					)

								# Take the EMA step.
								ema_unet.step(unet_pseudo_updated_step_one.parameters()					)

								# Now the EMA'd parameters won't be equal to the original model parameters.
								_lowerCAmelCase			:			Tuple        =					list(unet_pseudo_updated_step_one.parameters()					)
								for s_param, param in zip(ema_unet.shadow_params						,		_UpperCAmelCase					):
												assert ~torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)

								# Ensure this is the case when we take multiple EMA steps.
								for _ in range(4					):
												ema_unet.step(unet.parameters()					)
								for s_param, param in zip(ema_unet.shadow_params						,		_UpperCAmelCase					):
												assert ~torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]					)     ->			Tuple:





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			str        =					self.get_models()

								# First backprop + EMA
								_lowerCAmelCase			:			Optional[int]        =					self.simulate_backprop(_UpperCAmelCase					)
								ema_unet.step(unet_step_one.parameters()					)
								_lowerCAmelCase			:			List[str]        =					ema_unet.shadow_params

								# Second backprop + EMA
								_lowerCAmelCase			:			Optional[int]        =					self.simulate_backprop(_UpperCAmelCase					)
								ema_unet.step(unet_step_two.parameters()					)
								_lowerCAmelCase			:			Tuple        =					ema_unet.shadow_params

								for step_one, step_two in zip(_UpperCAmelCase						,		_UpperCAmelCase					):
												assert ~torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[Any]					)     ->			str:





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			int        =					self.get_models(decay=0.0					)
								_lowerCAmelCase			:			Dict        =					self.simulate_backprop(_UpperCAmelCase					)
								ema_unet.step(unet_step_one.parameters()					)
								_lowerCAmelCase			:			Any        =					ema_unet.shadow_params

								_lowerCAmelCase			:			List[Any]        =					self.simulate_backprop(_UpperCAmelCase					)
								ema_unet.step(unet_step_two.parameters()					)
								_lowerCAmelCase			:			int        =					ema_unet.shadow_params

								for step_one, step_two in zip(_UpperCAmelCase						,		_UpperCAmelCase					):
												assert torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase					)



				@skip_mps
				def 					SCREAMING_SNAKE_CASE				(					self					:						Union[str, Any]					)     ->			str:





								'''simple docstring'''




								_lowerCAmelCase    ,			_lowerCAmelCase			:			Tuple        =					self.get_models()
								_lowerCAmelCase    ,			_lowerCAmelCase    ,			_lowerCAmelCase			:			Tuple        =					self.get_dummy_inputs()

								with tempfile.TemporaryDirectory() as tmpdir:
												ema_unet.save_pretrained(_UpperCAmelCase					)
												_lowerCAmelCase			:			Union[str, Any]        =					UNetaDConditionModel.from_pretrained(_UpperCAmelCase						,		model_cls=_UpperCAmelCase					)
												_lowerCAmelCase			:			Any        =					loaded_unet.to(unet.device					)

								# Since no EMA step has been performed the outputs should match.
								_lowerCAmelCase			:			str        =					unet(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					).sample
								_lowerCAmelCase			:			Union[str, Any]        =					loaded_unet(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					).sample

								assert torch.allclose(_UpperCAmelCase						,		_UpperCAmelCase						,		atol=1E-4					)

