


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

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







class 					lowerCAmelCase__	(    a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			RetriBertConfig
     __SCREAMING_SNAKE_CASE        =			None
     __SCREAMING_SNAKE_CASE        =			"retribert"


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase)      ->    List[Any]:
            if isinstance(__lowerCamelCase			,						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(__lowerCamelCase			,						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(__lowerCamelCase			,						nn.LayerNorm):
                   module.bias.data.zero_()
                   module.weight.data.fill_(1.0)




lowerCAmelCase__						=			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 					lowerCAmelCase__	(    a):




     '''simple docstring'''


     def __init__(						self			,						__lowerCamelCase)      ->    None:
            super().__init__(__lowerCamelCase)
            _A				:	Optional[Any]       =			config.projection_dim

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

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

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


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

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

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


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase=None			,						__lowerCamelCase=-1			,						)      ->    List[str]:
            _A				:	Tuple       =			self.embed_sentences_checkpointed(
                __lowerCamelCase			,						__lowerCamelCase			,						self.bert_query			,						__lowerCamelCase			,						)
            return self.project_query(__lowerCamelCase)


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase=None			,						__lowerCamelCase=-1			,						)      ->    Union[str, Any]:
            _A				:	Union[str, Any]       =			self.embed_sentences_checkpointed(
                __lowerCamelCase			,						__lowerCamelCase			,						self.bert_query if self.bert_doc is None else self.bert_doc			,						__lowerCamelCase			,						)
            return self.project_doc(__lowerCamelCase)


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase = -1			,						)      ->    torch.FloatTensor:
            _A				:	Optional[Any]       =			input_ids_query.device
            _A				:	Tuple       =			self.embed_questions(__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase)
            _A				:	Optional[int]       =			self.embed_answers(__lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase)
            _A				:	Optional[int]       =			torch.mm(__lowerCamelCase			,						a_reps.t())
            _A				:	str       =			self.ce_loss(__lowerCamelCase			,						torch.arange(compare_scores.shape[1]).to(__lowerCamelCase))
            _A				:	int       =			self.ce_loss(compare_scores.t()			,						torch.arange(compare_scores.shape[0]).to(__lowerCamelCase))
            _A				:	Dict       =			(loss_qa + loss_aq) / 2
            return loss




from typing import List

import datasets
from datasets.tasks import ImageClassification

from ..folder_based_builder import folder_based_builder


lowerCAmelCase__						=			datasets.utils.logging.get_logger(__name__)







class 					lowerCAmelCase__	(    folder_based_builder.FolderBasedBuilderConfig):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			None
     __SCREAMING_SNAKE_CASE        =			None







class 					lowerCAmelCase__	(    folder_based_builder.FolderBasedBuilder):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			datasets.Image()
     __SCREAMING_SNAKE_CASE        =			"image"
     __SCREAMING_SNAKE_CASE        =			ImageFolderConfig
     __SCREAMING_SNAKE_CASE        =			42  # definition at the bottom of the script
     __SCREAMING_SNAKE_CASE        =			ImageClassification(image_column="image"					,   label_column="label")




lowerCAmelCase__						=			[
    '.blp',
    '.bmp',
    '.dib',
    '.bufr',
    '.cur',
    '.pcx',
    '.dcx',
    '.dds',
    '.ps',
    '.eps',
    '.fit',
    '.fits',
    '.fli',
    '.flc',
    '.ftc',
    '.ftu',
    '.gbr',
    '.gif',
    '.grib',
    '.h5',
    '.hdf',
    '.png',
    '.apng',
    '.jp2',
    '.j2k',
    '.jpc',
    '.jpf',
    '.jpx',
    '.j2c',
    '.icns',
    '.ico',
    '.im',
    '.iim',
    '.tif',
    '.tiff',
    '.jfif',
    '.jpe',
    '.jpg',
    '.jpeg',
    '.mpg',
    '.mpeg',
    '.msp',
    '.pcd',
    '.pxr',
    '.pbm',
    '.pgm',
    '.ppm',
    '.pnm',
    '.psd',
    '.bw',
    '.rgb',
    '.rgba',
    '.sgi',
    '.ras',
    '.tga',
    '.icb',
    '.vda',
    '.vst',
    '.webp',
    '.wmf',
    '.emf',
    '.xbm',
    '.xpm',
]
lowerCAmelCase__						=			IMAGE_EXTENSIONS
