import unittest
from unittest.util import safe_repr

from transformers import AutoTokenizer, RwkvConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          RWKV_PRETRAINED_MODEL_ARCHIVE_LIST,
          RwkvForCausalLM,
          RwkvModel,
      )
      from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
else:
      UpperCamelCase													=		False



class 						snake_case_ :






   def __init__(   self       :  Dict			,		lowercase_       :  Dict			,		lowercase_       :  Union[str, Any]=14			,		lowercase_       :  str=7			,		lowercase_       :  List[str]=True			,		lowercase_       :  Optional[Any]=False			,		lowercase_       :  Any=True			,		lowercase_       :  Tuple=True			,		lowercase_       :  List[Any]=True			,		lowercase_       :  List[str]=99			,		lowercase_       :  Any=32			,		lowercase_       :  Dict=5			,		lowercase_       :  List[Any]=37			,		lowercase_       :  Union[str, Any]="gelu"			,		lowercase_       :  int=0.1			,		lowercase_       :  Optional[int]=0.1			,		lowercase_       :  Union[str, Any]=5_12			,		lowercase_       :  Optional[int]=16			,		lowercase_       :  str=2			,		lowercase_       :  Any=3			,		lowercase_       :  str=4			,		lowercase_       :  Any=None			,		)      ->		Dict:
       lowercase__				:     Tuple					      =       parent
       lowercase__				:     Optional[Any]					      =       batch_size
       lowercase__				:     str					      =       seq_length
       lowercase__				:     Tuple					      =       is_training
       lowercase__				:     Optional[Any]					      =       use_token_type_ids
       lowercase__				:     Any					      =       use_input_mask
       lowercase__				:     str					      =       use_labels
       lowercase__				:     Tuple					      =       use_mc_token_ids
       lowercase__				:     Tuple					      =       vocab_size
       lowercase__				:     Tuple					      =       hidden_size
       lowercase__				:     int					      =       num_hidden_layers
       lowercase__				:     List[Any]					      =       intermediate_size
       lowercase__				:     str					      =       hidden_act
       lowercase__				:     List[str]					      =       hidden_dropout_prob
       lowercase__				:     List[Any]					      =       attention_probs_dropout_prob
       lowercase__				:     Any					      =       max_position_embeddings
       lowercase__				:     List[str]					      =       type_vocab_size
       lowercase__				:     Dict					      =       type_sequence_label_size
       lowercase__				:     List[str]					      =       num_labels
       lowercase__				:     Optional[int]					      =       num_choices
       lowercase__				:     Optional[int]					      =       scope
       lowercase__				:     Any					      =       vocab_size - 1
       lowercase__				:     Optional[int]					      =       vocab_size - 1
       lowercase__				:     int					      =       vocab_size - 1






   def    __UpperCamelCase  (   self       :  List[str]						)      ->		int:
       return RwkvConfig.from_pretrained("sgugger/rwkv-4-pile-7b"						)






   def    __UpperCamelCase  (   self       :  int			,		lowercase_       :  int=False			,		lowercase_       :  Union[str, Any]=False			,		lowercase_       :  List[Any]=False						)      ->		Optional[int]:
       lowercase__				:     str					      =       ids_tensor([self.batch_size, self.seq_length]			,		self.vocab_size						)

       lowercase__				:     Optional[Any]					      =       None
       if self.use_input_mask:
           lowercase__				:     Optional[int]					      =       random_attention_mask([self.batch_size, self.seq_length]						)

       lowercase__				:     List[str]					      =       None
       if self.use_token_type_ids:
           lowercase__				:     Optional[Any]					      =       ids_tensor([self.batch_size, self.seq_length]			,		self.type_vocab_size						)

       lowercase__				:     Dict					      =       None
       if self.use_mc_token_ids:
           lowercase__				:     List[Any]					      =       ids_tensor([self.batch_size, self.num_choices]			,		self.seq_length						)

       lowercase__				:     int					      =       None
       lowercase__				:     Dict					      =       None
       lowercase__				:     Union[str, Any]					      =       None
       if self.use_labels:
           lowercase__				:     List[Any]					      =       ids_tensor([self.batch_size]			,		self.type_sequence_label_size						)
           lowercase__				:     str					      =       ids_tensor([self.batch_size, self.seq_length]			,		self.num_labels						)
           lowercase__				:     List[Any]					      =       ids_tensor([self.batch_size]			,		self.num_choices						)

       lowercase__				:     List[Any]					      =       self.get_config(
           gradient_checkpointing=lowercase_			,		scale_attn_by_inverse_layer_idx=lowercase_			,		reorder_and_upcast_attn=lowercase_			,		)

       return (
           config,
           input_ids,
           input_mask,
           None,
           token_type_ids,
           mc_token_ids,
           sequence_labels,
           token_labels,
           choice_labels,
       )






   def    __UpperCamelCase  (   self       :  List[str]			,		lowercase_       :  str=False			,		lowercase_       :  Optional[int]=False			,		lowercase_       :  List[Any]=False						)      ->		Union[str, Any]:
       return RwkvConfig(
           vocab_size=self.vocab_size			,		hidden_size=self.hidden_size			,		num_hidden_layers=self.num_hidden_layers			,		intermediate_size=self.intermediate_size			,		activation_function=self.hidden_act			,		resid_pdrop=self.hidden_dropout_prob			,		attn_pdrop=self.attention_probs_dropout_prob			,		n_positions=self.max_position_embeddings			,		type_vocab_size=self.type_vocab_size			,		use_cache=lowercase_			,		bos_token_id=self.bos_token_id			,		eos_token_id=self.eos_token_id			,		pad_token_id=self.pad_token_id			,		gradient_checkpointing=lowercase_			,		scale_attn_by_inverse_layer_idx=lowercase_			,		reorder_and_upcast_attn=lowercase_			,		)






   def    __UpperCamelCase  (   self       :  Union[str, Any]						)      ->		str:
       lowercase__				:     Optional[Any]					      =       self.get_config()
       lowercase__				:     Any					      =       3_00
       return config






   def    __UpperCamelCase  (   self       :  Optional[Any]						)      ->		int:
       (
           (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     
       )				:     int					      =       self.prepare_config_and_inputs()

       lowercase__				:     Optional[Any]					      =       floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
       lowercase__				:     Optional[Any]					      =       ids_tensor([self.batch_size, self.seq_length]			,		vocab_size=2						)

       return (
           config,
           input_ids,
           input_mask,
           head_mask,
           token_type_ids,
           sequence_labels,
           token_labels,
           choice_labels,
           encoder_hidden_states,
           encoder_attention_mask,
       )






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  Optional[Any]			,		lowercase_       :  List[str]			,		lowercase_       :  List[str]			,		lowercase_       :  str			,		lowercase_       :  str			,		*lowercase_       :  Dict						)      ->		List[str]:
       lowercase__				:     Tuple					      =       True
       lowercase__				:     List[Any]					      =       RwkvModel(config=lowercase_						)
       model.to(lowercase_						)
       model.eval()

       lowercase__				:     Optional[Any]					      =       model(lowercase_						)

       self.parent.assertEqual(result.last_hidden_state.shape			,		(self.batch_size, self.seq_length, self.hidden_size)						)
       self.parent.assertEqual(len(result.hidden_states						)			,		config.num_hidden_layers + 1						)






   def    __UpperCamelCase  (   self       :  Optional[int]			,		lowercase_       :  List[str]			,		lowercase_       :  str			,		lowercase_       :  Any			,		lowercase_       :  int			,		lowercase_       :  Optional[Any]			,		*lowercase_       :  List[str]						)      ->		Union[str, Any]:
       lowercase__				:     List[Any]					      =       RwkvForCausalLM(lowercase_						)
       model.to(lowercase_						)
       model.eval()

       lowercase__				:     Union[str, Any]					      =       model(lowercase_			,		labels=lowercase_						)
       self.parent.assertEqual(result.loss.shape			,		()						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.vocab_size)						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  List[Any]			,		lowercase_       :  Dict			,		lowercase_       :  Dict			,		lowercase_       :  Tuple			,		lowercase_       :  int			,		*lowercase_       :  Optional[Any]						)      ->		int:
       lowercase__				:     List[Any]					      =       RwkvModel(config=lowercase_						)
       model.to(lowercase_						)
       model.eval()

       lowercase__				:     Union[str, Any]					      =       model(lowercase_						)
       lowercase__				:     Optional[int]					      =       outputs.last_hidden_state

       lowercase__				:     Any					      =       model(input_ids[:, :2]						)
       lowercase__				:     Optional[int]					      =       outputs.last_hidden_state

       # Using the state computed on the first inputs, we will get the same output
       lowercase__				:     Tuple					      =       model(input_ids[:, 2:]			,		state=outputs.state						)
       lowercase__				:     List[str]					      =       outputs.last_hidden_state

       self.parent.assertTrue(torch.allclose(torch.cat([output_one, output_two]			,		dim=1						)			,		lowercase_			,		atol=1E-5						)						)






   def    __UpperCamelCase  (   self       :  Optional[int]			,		lowercase_       :  Dict			,		lowercase_       :  List[Any]			,		lowercase_       :  Any			,		lowercase_       :  Optional[int]			,		lowercase_       :  Tuple			,		*lowercase_       :  List[str]			,		lowercase_       :  str=False						)      ->		List[Any]:
       lowercase__				:     str					      =       RwkvForCausalLM(lowercase_						)
       model.to(lowercase_						)
       if gradient_checkpointing:
           model.gradient_checkpointing_enable()

       lowercase__				:     Any					      =       model(lowercase_			,		labels=lowercase_						)
       self.parent.assertEqual(result.loss.shape			,		()						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.vocab_size)						)
       result.loss.backward()







   def    __UpperCamelCase  (   self       :  List[Any]						)      ->		Optional[Any]:
       lowercase__				:     Tuple					      =       self.prepare_config_and_inputs()

       (
           (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     (
           lowercase__
       )      ,     
       )				:     str					      =       config_and_inputs

       lowercase__				:     Optional[int]					      =       {"input_ids": input_ids}

       return config, inputs_dict



@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0						,reason="See https://github.com/huggingface/transformers/pull/24204" )
@require_torch
class 						snake_case_ (	__A						,__A						,__A						,unittest.TestCase ):
   __A			:	Tuple        =       (RwkvModel, RwkvForCausalLM) if is_torch_available() else ()
   __A			:	str        =       (
       {"feature-extraction": RwkvModel, "text-generation": RwkvForCausalLM} if is_torch_available() else {}
   )
   # all_generative_model_classes = (RwkvForCausalLM,) if is_torch_available() else ()
   __A			:	List[Any]        =       False
   __A			:	List[str]        =       False
   __A			:	Union[str, Any]        =       False
   __A			:	int        =       False
   __A			:	Union[str, Any]        =       False  # Rwkv does not support head masking






   def    __UpperCamelCase  (   self       :  Optional[int]						)      ->		Union[str, Any]:
       lowercase__				:     str					      =       RwkvModelTester(self						)
       lowercase__				:     Optional[int]					      =       ConfigTester(
           self			,		config_class=lowercase_			,		n_embd=37			,		common_properties=["hidden_size", "num_hidden_layers"]						)






   def    __UpperCamelCase  (   self       :  Tuple			,		lowercase_       :  Dict			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Any=None						)      ->		List[Any]:
       if isinstance(lowercase_			,		torch.Tensor						):
           lowercase__      ,     lowercase__				:     str					      =       member.max().item(), member.min().item()
       elif isinstance(lowercase_			,		lowercase_						) or isinstance(lowercase_			,		lowercase_						):
           lowercase__      ,     lowercase__				:     Optional[Any]					      =       max(lowercase_						), min(lowercase_						)

       if not isinstance(lowercase_			,		lowercase_						):
           raise TypeError("container should be a list or tuple"						)
       elif len(lowercase_						) != 2:
           raise ValueError("container should have 2 elements"						)

       lowercase__      ,     lowercase__				:     List[Any]					      =       container

       lowercase__				:     List[Any]					      =       (min_value >= expected_min) and (max_value <= expected_max)

       if not is_inside_interval:
           lowercase__				:     int					      =       "%s not found in %s" % (safe_repr(lowercase_						), safe_repr(lowercase_						))
           self.fail(self._formatMessage(lowercase_			,		lowercase_						)						)






   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Tuple:
       self.config_tester.run_common_tests()






   def    __UpperCamelCase  (   self       :  Tuple						)      ->		Optional[Any]:
       lowercase__				:     str					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_rwkv_model(*lowercase_						)






   def    __UpperCamelCase  (   self       :  Any						)      ->		List[Any]:
       lowercase__				:     Optional[Any]					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_causl_lm(*lowercase_						)






   def    __UpperCamelCase  (   self       :  Any						)      ->		Optional[int]:
       lowercase__				:     Dict					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_state_equivalency(*lowercase_						)






   def    __UpperCamelCase  (   self       :  Dict						)      ->		Any:
       lowercase__      ,     lowercase__				:     Tuple					      =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           lowercase__				:     int					      =       model_class(config=lowercase_						)
           for name, param in model.named_parameters():
               if "time_decay" in name:
                   if param.requires_grad:
                       self.assertTrue(param.data.max().item() == 3.0						)
                       self.assertTrue(param.data.min().item() == -5.0						)
               elif "time_first" in name:
                   if param.requires_grad:
                       # check if it's a ones like
                       self.assertTrue(torch.allclose(param.data			,		torch.ones_like(param.data						)			,		atol=1E-5			,		rtol=1E-5						)						)
               elif any(x in name for x in ["time_mix_key", "time_mix_receptance"]						):
                   if param.requires_grad:
                       self.assertInterval(
                           param.data			,		[0.0, 1.0]			,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''			,		)
               elif "time_mix_value" in name:
                   if param.requires_grad:
                       self.assertInterval(
                           param.data			,		[0.0, 1.3]			,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''			,		)






   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Union[str, Any]:
       lowercase__      ,     lowercase__				:     List[str]					      =       self.model_tester.prepare_config_and_inputs_for_common()
       lowercase__				:     Any					      =       True

       lowercase__				:     List[str]					      =       getattr(self.model_tester			,		"seq_length"			,		lowercase_						)

       for model_class in self.all_model_classes:
           lowercase__				:     List[str]					      =       True
           lowercase__				:     Any					      =       False
           lowercase__				:     List[str]					      =       True
           lowercase__				:     str					      =       model_class(lowercase_						)
           model.to(lowercase_						)
           model.eval()

           lowercase__				:     List[Any]					      =       self._prepare_for_class(lowercase_			,		lowercase_						)
           lowercase__				:     int					      =       inputs["input_ids"].shape[0]
           with torch.no_grad():
               lowercase__				:     List[str]					      =       model(**lowercase_						)
           lowercase__				:     Optional[int]					      =       outputs.attentions
           self.assertEqual(len(lowercase_						)			,		self.model_tester.num_hidden_layers						)

           # check that output_attentions also work using config
           del inputs_dict["output_attentions"]
           lowercase__				:     List[Any]					      =       True
           lowercase__				:     Any					      =       model_class(lowercase_						)
           model.to(lowercase_						)
           model.eval()

           lowercase__				:     Any					      =       self._prepare_for_class(lowercase_			,		lowercase_						)
           lowercase__				:     List[str]					      =       inputs["input_ids"].shape[0]
           with torch.no_grad():
               lowercase__				:     List[Any]					      =       model(**lowercase_						)
           lowercase__				:     Any					      =       outputs.attentions
           self.assertEqual(len(lowercase_						)			,		self.model_tester.num_hidden_layers						)

           self.assertListEqual(
               list(attentions[0].shape[-3:]						)			,		[batch_size, seq_len, config.hidden_size]			,		)
           lowercase__				:     List[str]					      =       len(lowercase_						)

           # Check attention is always last and order is fine
           lowercase__				:     int					      =       True
           lowercase__				:     List[Any]					      =       True
           lowercase__				:     int					      =       model_class(lowercase_						)
           model.to(lowercase_						)
           model.eval()

           lowercase__				:     str					      =       self._prepare_for_class(lowercase_			,		lowercase_						)
           lowercase__				:     int					      =       inputs["input_ids"].shape[0]
           with torch.no_grad():
               lowercase__				:     Union[str, Any]					      =       model(**lowercase_						)

           lowercase__				:     str					      =       1
           self.assertEqual(out_len + added_hidden_states			,		len(lowercase_						)						)

           lowercase__				:     Dict					      =       outputs.attentions

           self.assertEqual(len(lowercase_						)			,		self.model_tester.num_hidden_layers						)
           self.assertListEqual(
               list(self_attentions[0].shape[-3:]						)			,		[batch_size, seq_len, config.hidden_size]			,		)







   @slow
   def    __UpperCamelCase  (   self       :  Tuple						)      ->		str:
       for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase__				:     Tuple					      =       RwkvModel.from_pretrained(lowercase_						)
           self.assertIsNotNone(lowercase_						)



@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0						,reason="See https://github.com/huggingface/transformers/pull/24204" )
@slow
class 						snake_case_ (	unittest.TestCase ):






   def    __UpperCamelCase  (   self       :  Tuple						)      ->		Tuple:
       lowercase__				:     Union[str, Any]					      =       "RWKV/rwkv-4-169m-pile"
       lowercase__				:     Tuple					      =       AutoTokenizer.from_pretrained(self.model_id						)






   def    __UpperCamelCase  (   self       :  str						)      ->		Any:
       lowercase__				:     int					      =       "Hello my name is Jasmine and I am a newbie to the"
       lowercase__				:     Dict					      =       RwkvForCausalLM.from_pretrained(self.model_id						).to(lowercase_						)

       lowercase__				:     Tuple					      =       self.tokenizer("Hello my name is"			,		return_tensors="pt"						).input_ids.to(lowercase_						)
       lowercase__				:     Optional[int]					      =       model.generate(lowercase_			,		max_new_tokens=10						)
       lowercase__				:     Any					      =       self.tokenizer.decode(output[0].tolist()						)

       self.assertEqual(lowercase_			,		lowercase_						)







   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Union[str, Any]:
       lowercase__				:     List[str]					      =       "Hello my name is Jasmine and I am a newbie to the"

       lowercase__				:     List[str]					      =       self.tokenizer("Hello my name is"			,		return_tensors="pt"						).input_ids.to(lowercase_						)
       lowercase__				:     Optional[int]					      =       RwkvForCausalLM.from_pretrained(self.model_id			,		torch_dtype=torch.bfloataa						).to(lowercase_						)

       lowercase__				:     int					      =       model.generate(lowercase_			,		max_new_tokens=10						)
       lowercase__				:     Any					      =       self.tokenizer.decode(output[0].tolist()						)

       self.assertEqual(lowercase_			,		lowercase_						)




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


UpperCamelCase													=		logging.get_logger(__name__)

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



class 						snake_case_ (	__A ):
   __A			:	Optional[Any]        =       RetriBertConfig
   __A			:	str        =       None
   __A			:	Any        =       "retribert"






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



UpperCamelCase													=		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."						,__A						,)
class 						snake_case_ (	__A ):






   def __init__(   self       :  Dict			,		lowercase_       :  RetriBertConfig						)      ->		None:
       super().__init__(lowercase_						)
       lowercase__				:     str					      =       config.projection_dim

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

       lowercase__				:     Optional[Any]					      =       nn.CrossEntropyLoss(reduction="mean"						)

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






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

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

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






   def    __UpperCamelCase  (   self       :  Optional[Any]			,		lowercase_       :  Any			,		lowercase_       :  Any=None			,		lowercase_       :  Union[str, Any]=-1			,		)      ->		List[str]:
       lowercase__				:     Optional[Any]					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query			,		lowercase_			,		)
       return self.project_query(lowercase_						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Union[str, Any]=None			,		lowercase_       :  Dict=-1			,		)      ->		Optional[int]:
       lowercase__				:     str					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query if self.bert_doc is None else self.bert_doc			,		lowercase_			,		)
       return self.project_doc(lowercase_						)







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



