


import os
import tempfile
import unittest

import numpy as np
import torch

from diffusers.models import ModelMixin, UNetaDConditionModel
from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor
from diffusers.utils import (
    floats_tensor,
    logging,
    skip_mps,
    torch_device,
)
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

__UpperCamelCase							:							Tuple    							=					logging.get_logger(__name__)

def       _a	(					SCREAMING_SNAKE_CASE						:					List[str]     ,			SCREAMING_SNAKE_CASE						:					List[str] = True  ):







 """simple docstring"""



 UpperCamelCase__       :     Tuple 							= {}
 for name in model.attn_processors.keys():
  UpperCamelCase__       :     Any 							= name.endswith('''attn2.processor'''  ) and not (
      name.startswith('''transformer_in'''  ) or '''temp_attentions''' in name.split('''.'''  )
  )
  UpperCamelCase__       :     Union[str, Any] 							= model.config.cross_attention_dim if has_cross_attention else None
  if name.startswith('''mid_block'''  ):
   UpperCamelCase__       :     List[Any] 							= model.config.block_out_channels[-1]
  elif name.startswith('''up_blocks'''  ):
   UpperCamelCase__       :     Dict 							= int(name[len('''up_blocks.'''  )]  )
   UpperCamelCase__       :     Any 							= list(reversed(model.config.block_out_channels  )  )[block_id]
  elif name.startswith('''down_blocks'''  ):
   UpperCamelCase__       :     Dict 							= int(name[len('''down_blocks.'''  )]  )
   UpperCamelCase__       :     Union[str, Any] 							= model.config.block_out_channels[block_id]
  elif name.startswith('''transformer_in'''  ):
   # Note that the `8 * ...` comes from: https://github.com/huggingface/diffusers/blob/7139f0e874f10b2463caa8cbd585762a309d12d6/src/diffusers/models/unet_3d_condition.py#L148
   UpperCamelCase__       :     str 							= 8 * model.config.attention_head_dim

  UpperCamelCase__       :     Optional[Any] 							= LoRAAttnProcessor(hidden_size=lowercase_     ,			cross_attention_dim=lowercase_  )
  UpperCamelCase__       :     List[Any] 							= lora_attn_procs[name].to(model.device  )

  if mock_weights:
   # add 1 to weights to mock trained weights
   with torch.no_grad():
    lora_attn_procs[name].to_q_lora.up.weight += 1
    lora_attn_procs[name].to_k_lora.up.weight += 1
    lora_attn_procs[name].to_v_lora.up.weight += 1
    lora_attn_procs[name].to_out_lora.up.weight += 1

 return lora_attn_procs






@skip_mps
class    __magic_name__						(  _SCREAMING_SNAKE_CASE       ,					_SCREAMING_SNAKE_CASE       ,					unittest.TestCase):
     A:		Dict								=   UNetaDConditionModel
     A:		Any								=   "sample"


     @property
     def   UpperCAmelCase__						(   self				:  Any      )	->   Union[str, Any]:





      '''simple docstring'''






      UpperCamelCase__       :     List[Any] 							= 4
      UpperCamelCase__       :     Dict 							= 4
      UpperCamelCase__       :     str 							= 4
      UpperCamelCase__       :     List[str] 							= (32, 32)

      UpperCamelCase__       :     Optional[Any] 							= floats_tensor((batch_size, num_channels, num_frames) + sizes      ).to(lowerCamelCase__      )
      UpperCamelCase__       :     str 							= torch.tensor([10]      ).to(lowerCamelCase__      )
      UpperCamelCase__       :     Union[str, Any] 							= floats_tensor((batch_size, 4, 32)      ).to(lowerCamelCase__      )

      return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}


     @property
     def   UpperCAmelCase__						(   self				:  Tuple      )	->   Optional[Any]:





      '''simple docstring'''






      return (4, 4, 32, 32)


     @property
     def   UpperCAmelCase__						(   self				:  Optional[int]      )	->   Dict:





      '''simple docstring'''






      return (4, 4, 32, 32)


     def   UpperCAmelCase__						(   self				:  int      )	->   Optional[int]:





      '''simple docstring'''






      UpperCamelCase__       :     str 							= {
          '''block_out_channels''': (32, 64),
          '''down_block_types''': (
              '''CrossAttnDownBlock3D''',
              '''DownBlock3D''',
          ),
          '''up_block_types''': ('''UpBlock3D''', '''CrossAttnUpBlock3D'''),
          '''cross_attention_dim''': 32,
          '''attention_head_dim''': 8,
          '''out_channels''': 4,
          '''in_channels''': 4,
          '''layers_per_block''': 1,
          '''sample_size''': 32,
      }
      UpperCamelCase__       :     Optional[int] 							= self.dummy_input
      return init_dict, inputs_dict


     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()				,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''				,						)
     def   UpperCAmelCase__						(   self				:  Any      )	->   Tuple:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     List[Any] 							= self.prepare_init_args_and_inputs_for_common()
      UpperCamelCase__       :     Union[str, Any] 							= self.model_class(**lowerCamelCase__      )

      model.enable_xformers_memory_efficient_attention()

      assert (
          model.mid_block.attentions[0].transformer_blocks[0].attna.processor.__class__.__name__
          == "XFormersAttnProcessor"
      ), "xformers is not enabled"


     def   UpperCAmelCase__						(   self				:  str      )	->   List[str]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Union[str, Any] 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     Tuple 							= 32

      UpperCamelCase__       :     Optional[int] 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      model.eval()

      with torch.no_grad():
       UpperCamelCase__       :     Optional[int] 							= model(**lowerCamelCase__      )

       if isinstance(lowerCamelCase__				,						lowerCamelCase__      ):
        UpperCamelCase__       :     Union[str, Any] 							= output.sample

      self.assertIsNotNone(lowerCamelCase__      )
      UpperCamelCase__       :     Optional[Any] 							= inputs_dict['''sample'''].shape
      self.assertEqual(output.shape				,						lowerCamelCase__				,						'''Input and output shapes do not match'''      )


     def   UpperCAmelCase__						(   self				:  Union[str, Any]      )	->   Optional[int]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Union[str, Any] 							= self.prepare_init_args_and_inputs_for_common()
      UpperCamelCase__       :     List[Any] 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      model.eval()

      with torch.no_grad():
       # Warmup pass when using mps (see #372)
       if torch_device == "mps" and isinstance(lowerCamelCase__				,						lowerCamelCase__      ):
        model(**self.dummy_input      )

       UpperCamelCase__       :     Dict 							= model(**lowerCamelCase__      )
       if isinstance(lowerCamelCase__				,						lowerCamelCase__      ):
        UpperCamelCase__       :     int 							= first.sample

       UpperCamelCase__       :     str 							= model(**lowerCamelCase__      )
       if isinstance(lowerCamelCase__				,						lowerCamelCase__      ):
        UpperCamelCase__       :     Optional[int] 							= second.sample

      UpperCamelCase__       :     Any 							= first.cpu().numpy()
      UpperCamelCase__       :     int 							= second.cpu().numpy()
      UpperCamelCase__       :     Optional[Any] 							= out_a[~np.isnan(lowerCamelCase__      )]
      UpperCamelCase__       :     List[Any] 							= out_a[~np.isnan(lowerCamelCase__      )]
      UpperCamelCase__       :     Tuple 							= np.amax(np.abs(out_a - out_a      )      )
      self.assertLessEqual(lowerCamelCase__				,						1E-5      )


     def   UpperCAmelCase__						(   self				:  int      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Dict 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     List[str] 							= 8

      UpperCamelCase__       :     Any 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      model.eval()

      model.set_attention_slice('''auto'''      )
      with torch.no_grad():
       UpperCamelCase__       :     int 							= model(**lowerCamelCase__      )
      assert output is not None

      model.set_attention_slice('''max'''      )
      with torch.no_grad():
       UpperCamelCase__       :     List[Any] 							= model(**lowerCamelCase__      )
      assert output is not None

      model.set_attention_slice(2      )
      with torch.no_grad():
       UpperCamelCase__       :     Optional[Any] 							= model(**lowerCamelCase__      )
      assert output is not None


     def   UpperCAmelCase__						(   self				:  int      )	->   Dict:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     List[Any] 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     List[str] 							= 8

      UpperCamelCase__       :     Any 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     str 							= model(**lowerCamelCase__      ).sample

      UpperCamelCase__       :     Optional[Any] 							= create_lora_layers(lowerCamelCase__      )

      # make sure we can set a list of attention processors
      model.set_attn_processor(lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      # test that attn processors can be set to itself
      model.set_attn_processor(model.attn_processors      )

      with torch.no_grad():
       UpperCamelCase__       :     Any 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.0}      ).sample
       UpperCamelCase__       :     List[str] 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample
       UpperCamelCase__       :     List[str] 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample

      assert (samplea - samplea).abs().max() < 3E-3
      assert (samplea - samplea).abs().max() < 3E-3

      # sample 2 and sample 3 should be different
      assert (samplea - samplea).abs().max() > 3E-3


     def   UpperCAmelCase__						(   self				:  List[str]      )	->   Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Dict 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     Tuple 							= 8

      torch.manual_seed(0      )
      UpperCamelCase__       :     Tuple 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     Optional[Any] 							= model(**lowerCamelCase__      ).sample

      UpperCamelCase__       :     int 							= create_lora_layers(lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     Optional[int] 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample

      with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_attn_procs(lowerCamelCase__      )
       self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,						'''pytorch_lora_weights.bin'''      )      )      )
       torch.manual_seed(0      )
       UpperCamelCase__       :     Any 							= self.model_class(**lowerCamelCase__      )
       new_model.to(lowerCamelCase__      )
       new_model.load_attn_procs(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     str 							= new_model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample

      assert (sample - new_sample).abs().max() < 1E-3

      # LoRA and no LoRA should NOT be the same
      assert (sample - old_sample).abs().max() > 1E-4


     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Tuple:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     str 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     str 							= 8

      torch.manual_seed(0      )
      UpperCamelCase__       :     List[str] 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     List[Any] 							= model(**lowerCamelCase__      ).sample

      UpperCamelCase__       :     Dict 							= create_lora_layers(lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     Any 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample

      with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_attn_procs(lowerCamelCase__				,						safe_serialization=lowerCamelCase__      )
       self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,						'''pytorch_lora_weights.safetensors'''      )      )      )
       torch.manual_seed(0      )
       UpperCamelCase__       :     Any 							= self.model_class(**lowerCamelCase__      )
       new_model.to(lowerCamelCase__      )
       new_model.load_attn_procs(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     List[Any] 							= new_model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.5}      ).sample

      assert (sample - new_sample).abs().max() < 3E-3

      # LoRA and no LoRA should NOT be the same
      assert (sample - old_sample).abs().max() > 1E-4


     def   UpperCAmelCase__						(   self				:  Optional[int]      )	->   Tuple:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Tuple 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     Any 							= 8

      torch.manual_seed(0      )
      UpperCamelCase__       :     Any 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      UpperCamelCase__       :     Tuple 							= create_lora_layers(lowerCamelCase__				,						mock_weights=lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )
      # Saving as torch, properly reloads with directly filename
      with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_attn_procs(lowerCamelCase__      )
       self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,						'''pytorch_lora_weights.bin'''      )      )      )
       torch.manual_seed(0      )
       UpperCamelCase__       :     int 							= self.model_class(**lowerCamelCase__      )
       new_model.to(lowerCamelCase__      )
       new_model.load_attn_procs(lowerCamelCase__				,						weight_name='''pytorch_lora_weights.bin'''      )


     def   UpperCAmelCase__						(   self				:  List[str]      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Tuple 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     Optional[int] 							= 8

      torch.manual_seed(0      )
      UpperCamelCase__       :     Union[str, Any] 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      UpperCamelCase__       :     Optional[int] 							= create_lora_layers(lowerCamelCase__				,						mock_weights=lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )
      # Saving as torch, properly reloads with directly filename
      with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_attn_procs(lowerCamelCase__      )
       self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,						'''pytorch_lora_weights.bin'''      )      )      )
       torch.manual_seed(0      )
       UpperCamelCase__       :     List[Any] 							= self.model_class(**lowerCamelCase__      )
       new_model.to(lowerCamelCase__      )
       with self.assertRaises(lowerCamelCase__      ) as e:
        new_model.load_attn_procs(lowerCamelCase__				,						use_safetensors=lowerCamelCase__      )
       self.assertIn('''Error no file named pytorch_lora_weights.safetensors'''				,						str(e.exception      )      )


     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Tuple:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Optional[Any] 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     int 							= 8

      torch.manual_seed(0      )
      UpperCamelCase__       :     Tuple 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     Any 							= model(**lowerCamelCase__      ).sample

      UpperCamelCase__       :     Any 							= create_lora_layers(lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )

      with torch.no_grad():
       UpperCamelCase__       :     Union[str, Any] 							= model(**lowerCamelCase__				,						cross_attention_kwargs={'''scale''': 0.0}      ).sample

      model.set_attn_processor(AttnProcessor()      )

      with torch.no_grad():
       UpperCamelCase__       :     Union[str, Any] 							= model(**lowerCamelCase__      ).sample

      assert (sample - new_sample).abs().max() < 1E-4
      assert (sample - old_sample).abs().max() < 3E-3


     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()				,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''				,						)
     def   UpperCAmelCase__						(   self				:  Union[str, Any]      )	->   Optional[int]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Union[str, Any] 							= self.prepare_init_args_and_inputs_for_common()

      UpperCamelCase__       :     Optional[int] 							= 4

      torch.manual_seed(0      )
      UpperCamelCase__       :     int 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      UpperCamelCase__       :     Optional[int] 							= create_lora_layers(lowerCamelCase__      )
      model.set_attn_processor(lowerCamelCase__      )

      # default
      with torch.no_grad():
       UpperCamelCase__       :     List[Any] 							= model(**lowerCamelCase__      ).sample

       model.enable_xformers_memory_efficient_attention()
       UpperCamelCase__       :     int 							= model(**lowerCamelCase__      ).sample

       model.disable_xformers_memory_efficient_attention()
       UpperCamelCase__       :     Optional[Any] 							= model(**lowerCamelCase__      ).sample

      assert (sample - on_sample).abs().max() < 1E-4
      assert (sample - off_sample).abs().max() < 1E-4


     def   UpperCAmelCase__						(   self				:  Dict      )	->   Dict:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Any 							= self.prepare_init_args_and_inputs_for_common()
      UpperCamelCase__       :     Any 							= 32

      UpperCamelCase__       :     Union[str, Any] 							= self.model_class(**lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      model.eval()

      with torch.no_grad():
       UpperCamelCase__       :     Optional[Any] 							= model(**lowerCamelCase__      )[0]

      model.enable_forward_chunking()
      with torch.no_grad():
       UpperCamelCase__       :     int 							= model(**lowerCamelCase__      )[0]

      self.assertEqual(output.shape				,						output_a.shape				,						'''Shape doesn\'t match'''      )
      assert np.abs(output.cpu() - output_a.cpu()      ).max() < 1E-2


# (todo: sayakpaul) implement SLOW tests.








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 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      lowerCAmelCase__      :			Optional[Any]     =       RetriBertConfig
      lowerCAmelCase__      :			Optional[Any]     =       None
      lowerCAmelCase__      :			Dict     =       "retribert"







      def    snake_case						(  self       :			Dict			,							snake_case       :			Optional[Any]					):
          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_ 		=  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."				,      _SCREAMING_SNAKE_CASE				,      )
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      def __init__(  self       :			List[Any]			,							snake_case       :			RetriBertConfig					):
          super().__init__(snake_case					)
          __UpperCamelCase			=    config.projection_dim

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

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

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







      def    snake_case						(  self       :			Dict			,							snake_case       :			Dict			,							snake_case       :			List[str]			,							snake_case       :			Dict			,							snake_case       :			Any=-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
              __UpperCamelCase			=    input_ids.device
              __UpperCamelCase			=    input_ids.size()
              __UpperCamelCase			=    torch.zeros(snake_case			,							dtype=torch.long			,							device=snake_case					)
              __UpperCamelCase			=    [None] * sent_encoder.config.num_hidden_layers
              __UpperCamelCase			=    sent_encoder.get_extended_attention_mask(
                  snake_case			,							snake_case					)

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

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







      def    snake_case						(  self       :			Dict			,							snake_case       :			Any			,							snake_case       :			Union[str, Any]=None			,							snake_case       :			List[str]=-1			,							):
          __UpperCamelCase			=    self.embed_sentences_checkpointed(
              snake_case			,							snake_case			,							self.bert_query			,							snake_case			,							)
          return self.project_query(snake_case					)







      def    snake_case						(  self       :			Optional[Any]			,							snake_case       :			Optional[Any]			,							snake_case       :			Optional[int]=None			,							snake_case       :			Optional[Any]=-1			,							):
          __UpperCamelCase			=    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    snake_case						(  self       :			List[str]			,							snake_case       :			torch.LongTensor			,							snake_case       :			Optional[torch.FloatTensor]			,							snake_case       :			torch.LongTensor			,							snake_case       :			Optional[torch.FloatTensor]			,							snake_case       :			int = -1			,							):
          __UpperCamelCase			=    input_ids_query.device
          __UpperCamelCase			=    self.embed_questions(snake_case			,							snake_case			,							snake_case					)
          __UpperCamelCase			=    self.embed_answers(snake_case			,							snake_case			,							snake_case					)
          __UpperCamelCase			=    torch.mm(snake_case			,							a_reps.t()					)
          __UpperCamelCase			=    self.ce_loss(snake_case			,							torch.arange(compare_scores.shape[1]					).to(snake_case					)					)
          __UpperCamelCase			=    self.ce_loss(compare_scores.t()			,							torch.arange(compare_scores.shape[0]					).to(snake_case					)					)
          __UpperCamelCase			=    (loss_qa + loss_aq) / 2
          return loss






