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


SCREAMING_SNAKE_CASE__       =	logging.get_logger(__name__)

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



class 	lowerCAmelCase_     (      lowerCAmelCase       ):



				"""simple docstring"""
				_lowerCAmelCase  :     int      	=    RetriBertConfig
				_lowerCAmelCase  :     Tuple      	=    None
				_lowerCAmelCase  :     List[Any]      	=    """retribert"""

				def 		snake_case			(					self		,     lowerCAmelCase     ):






										"""simple docstring"""

										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     )





SCREAMING_SNAKE_CASE__       =	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		,     lowerCAmelCase     ):






										"""simple docstring"""

										super().__init__(lowerCAmelCase     )
										snake_case             =      config.projection_dim

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

										snake_case             =      nn.CrossEntropyLoss(reduction='mean'     )

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

				def 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase=-1		,     ):






										"""simple docstring"""

										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
																snake_case             =      input_ids.device
																snake_case             =      input_ids.size()
																snake_case             =      torch.zeros(lowerCAmelCase		,     dtype=torch.long		,     device=lowerCAmelCase     )
																snake_case             =      [None] * sent_encoder.config.num_hidden_layers
																snake_case             =      sent_encoder.get_extended_attention_mask(
																    lowerCAmelCase		,     lowerCAmelCase     )

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

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

				def 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase=None		,     lowerCAmelCase=-1		,     ):






										"""simple docstring"""

										snake_case             =      self.embed_sentences_checkpointed(
										    lowerCAmelCase		,     lowerCAmelCase		,     self.bert_query		,     lowerCAmelCase		,     )
										return self.project_query(lowerCAmelCase     )

				def 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase=None		,     lowerCAmelCase=-1		,     ):






										"""simple docstring"""

										snake_case             =      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 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase = -1		,     ):






										"""simple docstring"""

										snake_case             =      input_ids_query.device
										snake_case             =      self.embed_questions(lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase     )
										snake_case             =      self.embed_answers(lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase     )
										snake_case             =      torch.mm(lowerCAmelCase		,     a_reps.t()     )
										snake_case             =      self.ce_loss(lowerCAmelCase		,     torch.arange(compare_scores.shape[1]     ).to(lowerCAmelCase     )     )
										snake_case             =      self.ce_loss(compare_scores.t()		,     torch.arange(compare_scores.shape[0]     ).to(lowerCAmelCase     )     )
										snake_case             =      (loss_qa + loss_aq) / 2
										return loss



"""simple docstring"""
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import SwinaSRImageProcessor
					from transformers.image_transforms import get_image_size



class 	lowerCAmelCase_     (      unittest.TestCase       ):



				"""simple docstring"""

				def __init__(					self		,     lowerCAmelCase		,     lowerCAmelCase=7		,     lowerCAmelCase=3		,     lowerCAmelCase=18		,     lowerCAmelCase=30		,     lowerCAmelCase=4_00		,     lowerCAmelCase=True		,     lowerCAmelCase=1 / 2_55		,     lowerCAmelCase=True		,     lowerCAmelCase=8		,     ):






										"""simple docstring"""

										snake_case             =      parent
										snake_case             =      batch_size
										snake_case             =      num_channels
										snake_case             =      image_size
										snake_case             =      min_resolution
										snake_case             =      max_resolution
										snake_case             =      do_rescale
										snake_case             =      rescale_factor
										snake_case             =      do_pad
										snake_case             =      pad_size

				def 		snake_case			(					self     ):






										"""simple docstring"""

										return {
										    "do_rescale": self.do_rescale,
										    "rescale_factor": self.rescale_factor,
										    "do_pad": self.do_pad,
										    "pad_size": self.pad_size,
										}

				def 		snake_case			(					self		,     lowerCAmelCase=False		,     lowerCAmelCase=False		,     lowerCAmelCase=False     ):






										"""simple docstring"""

										assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

										if equal_resolution:
																snake_case             =      []
																for i in range(self.batch_size     ):
																						image_inputs.append(
																						    np.random.randint(
																						        2_55		,     size=(self.num_channels, self.max_resolution, self.max_resolution)		,     dtype=np.uinta     )     )
										else:
																snake_case             =      []
																for i in range(self.batch_size     ):
																						snake_case       ,snake_case             =      np.random.choice(np.arange(self.min_resolution		,     self.max_resolution     )		,     2     )
																						image_inputs.append(np.random.randint(2_55		,     size=(self.num_channels, width, height)		,     dtype=np.uinta     )     )

										if not numpify and not torchify:
																# PIL expects the channel dimension as last dimension
																snake_case             =      [Image.fromarray(np.moveaxis(lowerCAmelCase		,     0		,     -1     )     ) for x in image_inputs]

										if torchify:
																snake_case             =      [torch.from_numpy(lowerCAmelCase     ) for x in image_inputs]

										return image_inputs





@require_torch
@require_vision
class 	lowerCAmelCase_     (      lowerCAmelCase  ,     unittest.TestCase       ):



				"""simple docstring"""
				_lowerCAmelCase  :     Tuple      	=    SwinaSRImageProcessor if is_vision_available() else None

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      SwinaSRImageProcessingTester(self     )

				@property
				def 		snake_case			(					self     ):






										"""simple docstring"""

										return self.image_processor_tester.prepare_image_processor_dict()

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      self.image_processing_class(**self.image_processor_dict     )
										self.assertTrue(hasattr(lowerCAmelCase		,     'do_rescale'     )     )
										self.assertTrue(hasattr(lowerCAmelCase		,     'rescale_factor'     )     )
										self.assertTrue(hasattr(lowerCAmelCase		,     'do_pad'     )     )
										self.assertTrue(hasattr(lowerCAmelCase		,     'pad_size'     )     )

				def 		snake_case			(					self     ):






										"""simple docstring"""

										pass

				def 		snake_case			(					self		,     lowerCAmelCase     ):






										"""simple docstring"""

										snake_case       ,snake_case             =      get_image_size(lowerCAmelCase     )
										snake_case             =      self.image_processor_tester.pad_size

										snake_case             =      (old_height // size + 1) * size - old_height
										snake_case             =      (old_width // size + 1) * size - old_width
										return old_height + pad_height, old_width + pad_width

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      self.image_processing_class(**self.image_processor_dict     )
										# create random PIL images
										snake_case             =      self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase     )
										for image in image_inputs:
																self.assertIsInstance(lowerCAmelCase		,     Image.Image     )

										# Test not batched input
										snake_case             =      image_processor(image_inputs[0]		,     return_tensors='pt'     ).pixel_values
										snake_case       ,snake_case             =      self.calculate_expected_size(np.array(image_inputs[0]     )     )
										self.assertEqual(
										    encoded_images.shape		,     (
										        1,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )		,     )

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      self.image_processing_class(**self.image_processor_dict     )
										# create random numpy tensors
										snake_case             =      self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase		,     numpify=lowerCAmelCase     )
										for image in image_inputs:
																self.assertIsInstance(lowerCAmelCase		,     np.ndarray     )

										# Test not batched input
										snake_case             =      image_processor(image_inputs[0]		,     return_tensors='pt'     ).pixel_values
										snake_case       ,snake_case             =      self.calculate_expected_size(image_inputs[0]     )
										self.assertEqual(
										    encoded_images.shape		,     (
										        1,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )		,     )

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      self.image_processing_class(**self.image_processor_dict     )
										# create random PyTorch tensors
										snake_case             =      self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase		,     torchify=lowerCAmelCase     )
										for image in image_inputs:
																self.assertIsInstance(lowerCAmelCase		,     torch.Tensor     )

										# Test not batched input
										snake_case             =      image_processor(image_inputs[0]		,     return_tensors='pt'     ).pixel_values
										snake_case       ,snake_case             =      self.calculate_expected_size(image_inputs[0]     )
										self.assertEqual(
										    encoded_images.shape		,     (
										        1,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )		,     )


