
"""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   :      Tuple       =				logging.get_logger(__name__)

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






class   _UpperCAmelCase					(       _snake_case):
    __lowercase				:			Any	=       RetriBertConfig
    __lowercase				:			Union[str, Any]	=       None
    __lowercase				:			str	=       """retribert"""
    def        lowerCamelCase__						(     self    ,     snake_case_  ):
      if isinstance(snake_case_    ,     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(snake_case_    ,     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(snake_case_    ,     nn.LayerNorm  ):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0  )


_a   :      str       =				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    ,     snake_case_  ):
      super().__init__(snake_case_  )
      _snake_case  :    str            = config.projection_dim

      _snake_case  :    Tuple            = BertModel(snake_case_  )
      _snake_case  :    Dict            = None if config.share_encoders else BertModel(snake_case_  )
      _snake_case  :    List[Any]            = nn.Dropout(config.hidden_dropout_prob  )
      _snake_case  :    int            = nn.Linear(config.hidden_size    ,     config.projection_dim    ,     bias=snake_case_  )
      _snake_case  :    str            = nn.Linear(config.hidden_size    ,     config.projection_dim    ,     bias=snake_case_  )

      _snake_case  :    Union[str, Any]            = nn.CrossEntropyLoss(reduction="mean"  )

      # Initialize weights and apply final processing
      self.post_init()
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_=-1    ,     ):
      # reproduces BERT forward pass with checkpointing
      if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
        return sent_encoder(snake_case_    ,     attention_mask=snake_case_  )[1]
      else:
        # prepare implicit variables
        _snake_case  :    str            = input_ids.device
        _snake_case  :    Optional[int]            = input_ids.size()
        _snake_case  :    List[str]            = torch.zeros(snake_case_    ,     dtype=torch.long    ,     device=snake_case_  )
        _snake_case  :    Optional[Any]            = [None] * sent_encoder.config.num_hidden_layers
        _snake_case  :    torch.Tensor            = sent_encoder.get_extended_attention_mask(
            snake_case_    ,     snake_case_  )

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

        # run embedding layer on everything at once
        _snake_case  :    str            = sent_encoder.embeddings(
            input_ids=snake_case_    ,     position_ids=snake_case_    ,     token_type_ids=snake_case_    ,     inputs_embeds=snake_case_  )
        # run encoding and pooling on one mini-batch at a time
        _snake_case  :    Union[str, Any]            = []
        for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size  )  ):
          _snake_case  :    Union[str, Any]            = embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
          _snake_case  :    Any            = extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
          _snake_case  :    Optional[Any]            = checkpoint.checkpoint(snake_case_    ,     snake_case_    ,     snake_case_  )
          pooled_output_list.append(snake_case_  )
        return torch.cat(snake_case_    ,     dim=0  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_=None    ,     snake_case_=-1    ,     ):
      _snake_case  :    int            = self.embed_sentences_checkpointed(
          snake_case_    ,     snake_case_    ,     self.bert_query    ,     snake_case_    ,     )
      return self.project_query(snake_case_  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_=None    ,     snake_case_=-1    ,     ):
      _snake_case  :    Tuple            = self.embed_sentences_checkpointed(
          snake_case_    ,     snake_case_    ,     self.bert_query if self.bert_doc is None else self.bert_doc    ,     snake_case_    ,     )
      return self.project_doc(snake_case_  )


    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_ = -1    ,     ):
      _snake_case  :    Optional[Any]            = input_ids_query.device
      _snake_case  :    Union[str, Any]            = self.embed_questions(snake_case_    ,     snake_case_    ,     snake_case_  )
      _snake_case  :    Dict            = self.embed_answers(snake_case_    ,     snake_case_    ,     snake_case_  )
      _snake_case  :    Tuple            = torch.mm(snake_case_    ,     a_reps.t()  )
      _snake_case  :    Union[str, Any]            = self.ce_loss(snake_case_    ,     torch.arange(compare_scores.shape[1]  ).to(snake_case_  )  )
      _snake_case  :    Union[str, Any]            = self.ce_loss(compare_scores.t()    ,     torch.arange(compare_scores.shape[0]  ).to(snake_case_  )  )
      _snake_case  :    Optional[Any]            = (loss_qa + loss_aq) / 2
      return loss



"""simple docstring"""
import unittest

import numpy as np
from datasets import load_dataset

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, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import SegformerImageProcessor






class   _UpperCAmelCase					(       unittest.TestCase):
    def __init__(     self    ,     snake_case_    ,     snake_case_=7    ,     snake_case_=3    ,     snake_case_=30    ,     snake_case_=4_00    ,     snake_case_=True    ,     snake_case_=None    ,     snake_case_=True    ,     snake_case_=[0.5, 0.5, 0.5]    ,     snake_case_=[0.5, 0.5, 0.5]    ,     snake_case_=False    ,     ):
      _snake_case  :    List[str]            = size if size is not None else {"height": 30, "width": 30}
      _snake_case  :    Optional[int]            = parent
      _snake_case  :    Dict            = batch_size
      _snake_case  :    Any            = num_channels
      _snake_case  :    Optional[Any]            = min_resolution
      _snake_case  :    int            = max_resolution
      _snake_case  :    int            = do_resize
      _snake_case  :    List[Any]            = size
      _snake_case  :    int            = do_normalize
      _snake_case  :    Any            = image_mean
      _snake_case  :    str            = image_std
      _snake_case  :    List[Any]            = do_reduce_labels


    def        lowerCamelCase__						(     self  ):
      return {
          "do_resize": self.do_resize,
          "size": self.size,
          "do_normalize": self.do_normalize,
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_reduce_labels": self.do_reduce_labels,
      }


def 					a__ ( ):

  """simple docstring"""







  _snake_case  :    List[str]            = load_dataset("hf-internal-testing/fixtures_ade20k"							,  split="test"		)

  _snake_case  :    Any            = Image.open(dataset[0]["file"]		)
  _snake_case  :    Optional[int]            = Image.open(dataset[1]["file"]		)

  return image, map
def 					a__ ( ):

  """simple docstring"""







  _snake_case  :    Optional[int]            = load_dataset("hf-internal-testing/fixtures_ade20k"							,  split="test"		)

  _snake_case  :    Optional[int]            = Image.open(dataset[0]["file"]		)
  _snake_case  :    List[str]            = Image.open(dataset[1]["file"]		)
  _snake_case  :    Dict            = Image.open(dataset[2]["file"]		)
  _snake_case  :    List[str]            = Image.open(dataset[3]["file"]		)

  return [imagea, imagea], [mapa, mapa]






@require_torch
@require_vision
class   _UpperCAmelCase					(       _snake_case		,       unittest.TestCase):
    __lowercase				:			Dict	=       SegformerImageProcessor if is_vision_available() else None
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = SegformerImageProcessingTester(self  )
    @property
    def        lowerCamelCase__						(     self  ):
      return self.image_processor_tester.prepare_image_processor_dict()
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[Any]            = self.image_processing_class(**self.image_processor_dict  )
      self.assertTrue(hasattr(snake_case_    ,     "do_resize"  )  )
      self.assertTrue(hasattr(snake_case_    ,     "size"  )  )
      self.assertTrue(hasattr(snake_case_    ,     "do_normalize"  )  )
      self.assertTrue(hasattr(snake_case_    ,     "image_mean"  )  )
      self.assertTrue(hasattr(snake_case_    ,     "image_std"  )  )
      self.assertTrue(hasattr(snake_case_    ,     "do_reduce_labels"  )  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = self.image_processing_class.from_dict(self.image_processor_dict  )
      self.assertEqual(image_processor.size    ,     {"height": 30, "width": 30}  )
      self.assertEqual(image_processor.do_reduce_labels    ,     snake_case_  )

      _snake_case  :    int            = self.image_processing_class.from_dict(self.image_processor_dict    ,     size=42    ,     reduce_labels=snake_case_  )
      self.assertEqual(image_processor.size    ,     {"height": 42, "width": 42}  )
      self.assertEqual(image_processor.do_reduce_labels    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      pass
    def        lowerCamelCase__						(     self  ):
      # Initialize image_processing
      _snake_case  :    List[Any]            = self.image_processing_class(**self.image_processor_dict  )
      # create random PIL images
      _snake_case  :    List[str]            = prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=snake_case_  )
      for image in image_inputs:
        self.assertIsInstance(snake_case_    ,     Image.Image  )

      # Test not batched input
      _snake_case  :    Any            = image_processing(image_inputs[0]    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )

      # Test batched
      _snake_case  :    List[Any]            = image_processing(snake_case_    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
    def        lowerCamelCase__						(     self  ):
      # Initialize image_processing
      _snake_case  :    Optional[Any]            = self.image_processing_class(**self.image_processor_dict  )
      # create random numpy tensors
      _snake_case  :    Any            = prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=snake_case_    ,     numpify=snake_case_  )
      for image in image_inputs:
        self.assertIsInstance(snake_case_    ,     np.ndarray  )

      # Test not batched input
      _snake_case  :    Optional[int]            = image_processing(image_inputs[0]    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )

      # Test batched
      _snake_case  :    Optional[int]            = image_processing(snake_case_    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
    def        lowerCamelCase__						(     self  ):
      # Initialize image_processing
      _snake_case  :    Optional[int]            = self.image_processing_class(**self.image_processor_dict  )
      # create random PyTorch tensors
      _snake_case  :    Optional[Any]            = prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=snake_case_    ,     torchify=snake_case_  )
      for image in image_inputs:
        self.assertIsInstance(snake_case_    ,     torch.Tensor  )

      # Test not batched input
      _snake_case  :    Dict            = image_processing(image_inputs[0]    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )

      # Test batched
      _snake_case  :    List[Any]            = image_processing(snake_case_    ,     return_tensors="pt"  ).pixel_values
      self.assertEqual(
          encoded_images.shape    ,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
    def        lowerCamelCase__						(     self  ):
      # Initialize image_processing
      _snake_case  :    int            = self.image_processing_class(**self.image_processor_dict  )
      # create random PyTorch tensors
      _snake_case  :    List[str]            = prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=snake_case_    ,     torchify=snake_case_  )
      _snake_case  :    Optional[int]            = []
      for image in image_inputs:
        self.assertIsInstance(snake_case_    ,     torch.Tensor  )
        maps.append(torch.zeros(image.shape[-2:]  ).long()  )

      # Test not batched input
      _snake_case  :    Optional[Any]            = image_processing(image_inputs[0]    ,     maps[0]    ,     return_tensors="pt"  )
      self.assertEqual(
          encoding["pixel_values"].shape    ,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(
          encoding["labels"].shape    ,     (
              1,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(encoding["labels"].dtype    ,     torch.long  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 2_55  )

      # Test batched
      _snake_case  :    List[Any]            = image_processing(snake_case_    ,     snake_case_    ,     return_tensors="pt"  )
      self.assertEqual(
          encoding["pixel_values"].shape    ,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(
          encoding["labels"].shape    ,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(encoding["labels"].dtype    ,     torch.long  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 2_55  )

      # Test not batched input (PIL images)
      _snake_case      ,       _snake_case  :    int            = prepare_semantic_single_inputs()

      _snake_case  :    List[str]            = image_processing(snake_case_    ,     snake_case_    ,     return_tensors="pt"  )
      self.assertEqual(
          encoding["pixel_values"].shape    ,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(
          encoding["labels"].shape    ,     (
              1,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(encoding["labels"].dtype    ,     torch.long  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 2_55  )

      # Test batched input (PIL images)
      _snake_case      ,       _snake_case  :    str            = prepare_semantic_batch_inputs()

      _snake_case  :    List[Any]            = image_processing(snake_case_    ,     snake_case_    ,     return_tensors="pt"  )
      self.assertEqual(
          encoding["pixel_values"].shape    ,     (
              2,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(
          encoding["labels"].shape    ,     (
              2,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,     )
      self.assertEqual(encoding["labels"].dtype    ,     torch.long  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 2_55  )


    def        lowerCamelCase__						(     self  ):
      # Initialize image_processing
      _snake_case  :    List[Any]            = self.image_processing_class(**self.image_processor_dict  )

      # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
      _snake_case      ,       _snake_case  :    List[Any]            = prepare_semantic_single_inputs()
      _snake_case  :    Dict            = image_processing(snake_case_    ,     snake_case_    ,     return_tensors="pt"  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 1_50  )

      _snake_case  :    Tuple            = True
      _snake_case  :    Union[str, Any]            = image_processing(snake_case_    ,     snake_case_    ,     return_tensors="pt"  )
      self.assertTrue(encoding["labels"].min().item() >= 0  )
      self.assertTrue(encoding["labels"].max().item() <= 2_55  )

