




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





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_=10      ,  UpperCAmelCase_=10      ,  UpperCAmelCase_=False      ,  UpperCAmelCase_=False	):
    _a							:       Union[str, Any]       					=			[]
    for i in range(image_processor_tester.num_frames	):
        video.append(np.random.randint(255      ,  size=(image_processor_tester.num_channels, width, height)      ,  dtype=np.uinta	)	)

    if not numpify and not torchify:
        # PIL expects the channel dimension as last dimension
        _a							:       Dict       					=			[Image.fromarray(np.moveaxis(UpperCAmelCase_      ,  0      ,  -1	)	) for frame in video]

    if torchify:
        _a							:       Dict       					=			[torch.from_numpy(UpperCAmelCase_	) for frame in video]

    return video





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_=False      ,  UpperCAmelCase_=False      ,  UpperCAmelCase_=False	):
    assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

    _a							:       Optional[int]       					=			[]
    for i in range(image_processor_tester.batch_size	):
        if equal_resolution:
            _a							:       Tuple       					=			image_processor_tester.max_resolution
        else:
            _a					,   _a							:       Optional[int]       					=			np.random.choice(
                np.arange(image_processor_tester.min_resolution      ,  image_processor_tester.max_resolution	)      ,  2	)
            _a							:       List[Any]       					=			prepare_video(
                image_processor_tester=UpperCAmelCase_      ,  width=UpperCAmelCase_      ,  height=UpperCAmelCase_      ,  numpify=UpperCAmelCase_      ,  torchify=UpperCAmelCase_      ,  )
        video_inputs.append(UpperCAmelCase_	)

    return video_inputs




class     UpperCamelCase					(  unittest.TestCase					):



  def __init__( self		,    __lowerCAmelCase		,    __lowerCAmelCase=7		,    __lowerCAmelCase=3		,    __lowerCAmelCase=4		,    __lowerCAmelCase=18		,    __lowerCAmelCase=30		,    __lowerCAmelCase=400		,    __lowerCAmelCase=True		,    __lowerCAmelCase=None		,    __lowerCAmelCase=True		,    __lowerCAmelCase=[0.5, 0.5, 0.5]		,    __lowerCAmelCase=[0.5, 0.5, 0.5]		,    __lowerCAmelCase=True		,    __lowerCAmelCase=None		,    ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			size if size is not None else {"""shortest_edge""": 18}
      _a							:       Union[str, Any]       					=			crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

      _a							:       Optional[int]       					=			parent
      _a							:       Optional[int]       					=			batch_size
      _a							:       Optional[int]       					=			num_channels
      _a							:       Dict       					=			num_frames
      _a							:       Dict       					=			image_size
      _a							:       List[str]       					=			min_resolution
      _a							:       Any       					=			max_resolution
      _a							:       Optional[int]       					=			do_resize
      _a							:       Optional[int]       					=			size
      _a							:       List[str]       					=			do_normalize
      _a							:       List[Any]       					=			image_mean
      _a							:       str       					=			image_std
      _a							:       Optional[Any]       					=			do_center_crop
      _a							:       Any       					=			crop_size



  def 						a_       ( self   ):







      '''simple docstring'''


      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
      }






@require_torch
@require_vision
class     UpperCamelCase					(  snake_case__			,		unittest.TestCase					):
  a    :Union[str, Any]      					=				TvltImageProcessor if is_vision_available() else None



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Tuple       					=			TvltImageProcessorTester(self   )



  @property
  def 						a_       ( self   ):







      '''simple docstring'''


      return self.image_processor_tester.prepare_image_processor_dict()



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Tuple       					=			self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """image_mean"""   )   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """image_std"""   )   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """do_normalize"""   )   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """do_resize"""   )   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """do_center_crop"""   )   )
      self.assertTrue(hasattr(__lowerCAmelCase		,    """size"""   )   )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Optional[Any]       					=			self.image_processing_class(**self.image_processor_dict   )
      # create random PIL videos
      _a							:       Tuple       					=			prepare_video_inputs(self.image_processor_tester		,    equal_resolution=__lowerCAmelCase   )
      for video in video_inputs:
          self.assertIsInstance(__lowerCAmelCase		,    __lowerCAmelCase   )
          self.assertIsInstance(video[0]		,    Image.Image   )

      # Test not batched input
      _a							:       Optional[Any]       					=			image_processor(video_inputs[0]		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )

      # Test batched
      _a							:       Optional[Any]       					=			image_processor(__lowerCAmelCase		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Any       					=			self.image_processing_class(**self.image_processor_dict   )
      # create random numpy tensors
      _a							:       List[str]       					=			prepare_video_inputs(self.image_processor_tester		,    equal_resolution=__lowerCAmelCase		,    numpify=__lowerCAmelCase   )
      for video in video_inputs:
          self.assertIsInstance(__lowerCAmelCase		,    __lowerCAmelCase   )
          self.assertIsInstance(video[0]		,    np.ndarray   )

      # Test not batched input
      _a							:       List[str]       					=			image_processor(video_inputs[0]		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )

      # Test batched
      _a							:       Optional[Any]       					=			image_processor(__lowerCAmelCase		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       List[Any]       					=			self.image_processing_class(**self.image_processor_dict   )
      # create random PyTorch tensors
      _a							:       List[Any]       					=			prepare_video_inputs(self.image_processor_tester		,    equal_resolution=__lowerCAmelCase		,    torchify=__lowerCAmelCase   )
      for video in video_inputs:
          self.assertIsInstance(__lowerCAmelCase		,    __lowerCAmelCase   )
          self.assertIsInstance(video[0]		,    torch.Tensor   )

      # Test not batched input
      _a							:       List[Any]       					=			image_processor(video_inputs[0]		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )

      # Test batched
      _a							:       List[Any]       					=			image_processor(__lowerCAmelCase		,    return_tensors="""pt"""   ).pixel_values
      self.assertEqual(
          encoded_videos.shape		,    (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )		,    )








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

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




class     UpperCamelCase					(  snake_case__					):
  a    :List[Any]      					=				RetriBertConfig
  a    :int      					=				None
  a    :List[Any]      					=				'retribert'



  def 						a_       ( 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   )






a		:  Union[str, Any]   			=			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.'			,		snake_case__			,		)
class     UpperCamelCase					(  snake_case__					):



  def __init__( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      super().__init__(__lowerCAmelCase   )
      _a							:       Tuple       					=			config.projection_dim

      _a							:       int       					=			BertModel(__lowerCAmelCase   )
      _a							:       int       					=			None if config.share_encoders else BertModel(__lowerCAmelCase   )
      _a							:       Optional[int]       					=			nn.Dropout(config.hidden_dropout_prob   )
      _a							:       Dict       					=			nn.Linear(config.hidden_size		,    config.projection_dim		,    bias=__lowerCAmelCase   )
      _a							:       Any       					=			nn.Linear(config.hidden_size		,    config.projection_dim		,    bias=__lowerCAmelCase   )

      _a							:       Tuple       					=			nn.CrossEntropyLoss(reduction="""mean"""   )

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



  def 						a_       ( 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
          _a							:       Optional[int]       					=			input_ids.device
          _a							:       Optional[Any]       					=			input_ids.size()
          _a							:       str       					=			torch.zeros(__lowerCAmelCase		,    dtype=torch.long		,    device=__lowerCAmelCase   )
          _a							:       Optional[int]       					=			[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							:       Tuple       					=			sent_encoder.encoder(
                  inputs[0]		,    attention_mask=inputs[1]		,    head_mask=__lowerCAmelCase		,    )
              _a							:       List[str]       					=			encoder_outputs[0]
              _a							:       List[str]       					=			sent_encoder.pooler(__lowerCAmelCase   )
              return pooled_output

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



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase=None		,    __lowerCAmelCase=-1		,    ):







      '''simple docstring'''


      _a							:       Any       					=			self.embed_sentences_checkpointed(
          __lowerCAmelCase		,    __lowerCAmelCase		,    self.bert_query		,    __lowerCAmelCase		,    )
      return self.project_query(__lowerCAmelCase   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase=None		,    __lowerCAmelCase=-1		,    ):







      '''simple docstring'''


      _a							:       List[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 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase = -1		,    ):







      '''simple docstring'''


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


