

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


A									=						logging.get_logger(__name__)

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

class        _UpperCamelCase	(						SCREAMING_SNAKE_CASE_	):


  """simple docstring"""





  snake_case_        =    RetriBertConfig
  snake_case_        =    None
  snake_case_        =    'retribert'



  def 							_UpperCAmelCase      ( self					: Dict       ,       snake_case					: int      )	->			Union[str, Any]:


         '''simple docstring'''





         if isinstance(lowercase_       ,       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(lowercase_       ,       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(lowercase_       ,       nn.LayerNorm      ):
                module.bias.data.zero_()
                module.weight.data.fill_(1.0      )

A									=						R"""

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

@add_start_docstrings(
    'Bert Based model to embed queries or document for document retrieval.'   ,				SCREAMING_SNAKE_CASE_   ,				)
class        _UpperCamelCase	(						SCREAMING_SNAKE_CASE_	):


  """simple docstring"""





  def __init__( self					: Tuple       ,       snake_case					: RetriBertConfig      )	->			None:


         '''simple docstring'''





         super().__init__(lowercase_      )
         __magic_name__			:		Union[str, Any]        =     config.projection_dim

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

         __magic_name__			:		str        =     nn.CrossEntropyLoss(reduction='''mean'''      )

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



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


         '''simple docstring'''





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

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

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



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


         '''simple docstring'''





         __magic_name__			:		Dict        =     self.embed_sentences_checkpointed(
             lowercase_       ,       lowercase_       ,       self.bert_query       ,       lowercase_       ,       )
         return self.project_query(lowercase_      )



  def 							_UpperCAmelCase      ( self					: List[Any]       ,       snake_case					: Any       ,       snake_case					: int=None       ,       snake_case					: Any=-1       ,       )	->			Union[str, Any]:


         '''simple docstring'''





         __magic_name__			:		Optional[Any]        =     self.embed_sentences_checkpointed(
             lowercase_       ,       lowercase_       ,       self.bert_query if self.bert_doc is None else self.bert_doc       ,       lowercase_       ,       )
         return self.project_doc(lowercase_      )




  def 							_UpperCAmelCase      ( self					: Optional[int]       ,       snake_case					: torch.LongTensor       ,       snake_case					: Optional[torch.FloatTensor]       ,       snake_case					: torch.LongTensor       ,       snake_case					: Optional[torch.FloatTensor]       ,       snake_case					: int = -1       ,       )	->			torch.FloatTensor:


         '''simple docstring'''





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





"""simple docstring"""


import shutil

import requests

def 					_lowerCAmelCase (  lowercase_						,      lowercase_ = False						,      lowercase_ = "."		):
						UpperCAmelCase			 =					'https://api.nasa.gov/planetary/apod'
						return requests.get(lowercase_						,      params={'api_key': api_key}		).json()

def 					_lowerCAmelCase (  lowercase_						,      lowercase_ = "."		):
						UpperCAmelCase			 =					get_apod_data(lowercase_		)
						UpperCAmelCase			 =					apod_data['url']
						UpperCAmelCase			 =					img_url.split('/'		)[-1]
						UpperCAmelCase			 =					requests.get(lowercase_						,      stream=lowercase_		)

						with open(F"""{path}/{img_name}"""						,      'wb+'		) as img_file:
												shutil.copyfileobj(response.raw						,      lowercase_		)
						del response
						return apod_data

def 					_lowerCAmelCase (  lowercase_		):
						UpperCAmelCase			 =					'https://images-api.nasa.gov/search'
						return requests.get(lowercase_						,      params={'q': query}		).json()


if __name__ == "__main__":
				print(save_apod("""YOUR API KEY"""))
				snake_case_								=			get_archive_data("""apollo 2011""")["""collection"""]["""items"""]
				print(apollo_aaaa_items[0]["""data"""][0]["""description"""])





