



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


lowercase__     :  str    					=			logging.get_logger(__name__)

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

class       lowerCamelCase_							(	lowerCAmelCase_  ):






   '''simple docstring'''

   A :     str				=	RetriBertConfig
   A :     Union[str, Any]				=	None
   A :     str				=	"retribert"


   def 	_UpperCamelCase       (  self     ,						__UpperCamelCase ):
       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 )

lowercase__     :  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."					,    lowerCAmelCase_					,    )
class       lowerCamelCase_							(	lowerCAmelCase_  ):






   '''simple docstring'''

   def __init__(  self     ,						__UpperCamelCase ):
       super().__init__(__UpperCamelCase )
       UpperCamelCase__      =			config.projection_dim

       UpperCamelCase__      =			BertModel(__UpperCamelCase )
       UpperCamelCase__      =			None if config.share_encoders else BertModel(__UpperCamelCase )
       UpperCamelCase__      =			nn.Dropout(config.hidden_dropout_prob )
       UpperCamelCase__      =			nn.Linear(config.hidden_size     ,						config.projection_dim     ,						bias=__UpperCamelCase )
       UpperCamelCase__      =			nn.Linear(config.hidden_size     ,						config.projection_dim     ,						bias=__UpperCamelCase )

       UpperCamelCase__      =			nn.CrossEntropyLoss(reduction="mean" )

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


   def 	_UpperCamelCase       (  self     ,						__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase=-1     ,						):
       # 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
           UpperCamelCase__      =			input_ids.device
           UpperCamelCase__      =			input_ids.size()
           UpperCamelCase__      =			torch.zeros(__UpperCamelCase     ,						dtype=torch.long     ,						device=__UpperCamelCase )
           UpperCamelCase__      =			[None] * sent_encoder.config.num_hidden_layers
           UpperCamelCase__      =			sent_encoder.get_extended_attention_mask(
               __UpperCamelCase     ,						__UpperCamelCase )

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

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


   def 	_UpperCamelCase       (  self     ,						__UpperCamelCase     ,						__UpperCamelCase=None     ,						__UpperCamelCase=-1     ,						):
       UpperCamelCase__      =			self.embed_sentences_checkpointed(
           __UpperCamelCase     ,						__UpperCamelCase     ,						self.bert_query     ,						__UpperCamelCase     ,						)
       return self.project_query(__UpperCamelCase )


   def 	_UpperCamelCase       (  self     ,						__UpperCamelCase     ,						__UpperCamelCase=None     ,						__UpperCamelCase=-1     ,						):
       UpperCamelCase__      =			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     ,						__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase = -1     ,						):
       UpperCamelCase__      =			input_ids_query.device
       UpperCamelCase__      =			self.embed_questions(__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase )
       UpperCamelCase__      =			self.embed_answers(__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase )
       UpperCamelCase__      =			torch.mm(__UpperCamelCase     ,						a_reps.t() )
       UpperCamelCase__      =			self.ce_loss(__UpperCamelCase     ,						torch.arange(compare_scores.shape[1] ).to(__UpperCamelCase ) )
       UpperCamelCase__      =			self.ce_loss(compare_scores.t()     ,						torch.arange(compare_scores.shape[0] ).to(__UpperCamelCase ) )
       UpperCamelCase__      =			(loss_qa + loss_aq) / 2
       return loss









'''simple docstring'''







from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel
from ...schedulers import PNDMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput

class       lowerCamelCase_							(	lowerCAmelCase_  ):






   '''simple docstring'''

   A :     UNetaDModel
   A :     PNDMScheduler


   def __init__(  self     ,						__UpperCamelCase     ,						__UpperCamelCase ):
       super().__init__()

       UpperCamelCase__      =			PNDMScheduler.from_config(scheduler.config )

       self.register_modules(unet=__UpperCamelCase     ,						scheduler=__UpperCamelCase )







   @torch.no_grad()
   def __call__(  self     ,						__UpperCamelCase = 1     ,						__UpperCamelCase = 50     ,						__UpperCamelCase = None     ,						__UpperCamelCase = "pil"     ,						__UpperCamelCase = True     ,						**__UpperCamelCase     ,						):
       UpperCamelCase__      =			randn_tensor(
           (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size)     ,						generator=__UpperCamelCase     ,						device=self.device     ,						)

       self.scheduler.set_timesteps(__UpperCamelCase )
       for t in self.progress_bar(self.scheduler.timesteps ):
           UpperCamelCase__      =			self.unet(__UpperCamelCase     ,						__UpperCamelCase ).sample

           UpperCamelCase__      =			self.scheduler.step(__UpperCamelCase     ,						__UpperCamelCase     ,						__UpperCamelCase ).prev_sample

       UpperCamelCase__      =			(image / 2 + 0.5).clamp(0     ,						1 )
       UpperCamelCase__      =			image.cpu().permute(0     ,						2     ,						3     ,						1 ).numpy()
       if output_type == "pil":
           UpperCamelCase__      =			self.numpy_to_pil(__UpperCamelCase )

       if not return_dict:
           return (image,)

       return ImagePipelineOutput(images=__UpperCamelCase )




