




'''simple docstring'''





import tempfile
import unittest

import transformers
from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
  import jax
  import jax.numpy as jnp
  import numpy as np

  from transformers.modeling_flax_pytorch_utils import (
      convert_pytorch_state_dict_to_flax,
      load_flax_weights_in_pytorch_model,
  )
  from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel


if is_torch_available():
  import torch




@require_flax
class     UpperCamelCase					:



  def __init__( self		,    __lowerCAmelCase		,    __lowerCAmelCase=14		,    __lowerCAmelCase=7		,    __lowerCAmelCase=True		,    __lowerCAmelCase=True		,    __lowerCAmelCase=True		,    __lowerCAmelCase=99		,    __lowerCAmelCase=32		,    __lowerCAmelCase=5		,    __lowerCAmelCase=4		,    __lowerCAmelCase=37		,    __lowerCAmelCase="gelu"		,    __lowerCAmelCase=0.1		,    __lowerCAmelCase=0.1		,    __lowerCAmelCase=512		,    __lowerCAmelCase=0.02		,    __lowerCAmelCase=None		,    ):







      '''simple docstring'''


      _a							:       List[Any]       					=			parent
      _a							:       List[str]       					=			batch_size
      _a							:       List[Any]       					=			seq_length
      _a							:       int       					=			is_training
      _a							:       Union[str, Any]       					=			use_input_mask
      _a							:       List[str]       					=			use_labels
      _a							:       Dict       					=			vocab_size
      _a							:       str       					=			d_model
      _a							:       List[Any]       					=			num_hidden_layers
      _a							:       Tuple       					=			num_attention_heads
      _a							:       Dict       					=			ffn_dim
      _a							:       Any       					=			activation_function
      _a							:       Dict       					=			activation_dropout
      _a							:       List[str]       					=			attention_dropout
      _a							:       str       					=			max_position_embeddings
      _a							:       Tuple       					=			initializer_range
      _a							:       Tuple       					=			None
      _a							:       Any       					=			0
      _a							:       Any       					=			2
      _a							:       int       					=			1



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Tuple       					=			np.clip(ids_tensor([self.batch_size, self.seq_length]		,    self.vocab_size   )		,    3		,    self.vocab_size   )

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

      _a							:       Optional[int]       					=			XGLMConfig(
          vocab_size=self.vocab_size		,    d_model=self.hidden_size		,    num_layers=self.num_hidden_layers		,    attention_heads=self.num_attention_heads		,    ffn_dim=self.ffn_dim		,    activation_function=self.activation_function		,    activation_dropout=self.activation_dropout		,    attention_dropout=self.attention_dropout		,    max_position_embeddings=self.max_position_embeddings		,    initializer_range=self.initializer_range		,    use_cache=__UpperCamelCase		,    bos_token_id=self.bos_token_id		,    eos_token_id=self.eos_token_id		,    pad_token_id=self.pad_token_id		,    )

      return (config, input_ids, input_mask)



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Dict       					=			self.prepare_config_and_inputs()
      _a					,   _a					,   _a							:       List[Any]       					=			config_and_inputs
      _a							:       Tuple       					=			{"""input_ids""": input_ids, """attention_mask""": attention_mask}
      return config, inputs_dict



  def 						a_       ( self   ):







      '''simple docstring'''


      _a					,   _a					,   _a							:       Tuple       					=			self.prepare_config_and_inputs()

      _a							:       List[str]       					=			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]   )
      _a							:       int       					=			ids_tensor([self.batch_size, self.seq_length]		,    vocab_size=2   )

      return (
          config,
          input_ids,
          attention_mask,
          encoder_hidden_states,
          encoder_attention_mask,
      )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Optional[Any]       					=			20
      _a							:       Tuple       					=			model_class_name(__UpperCamelCase   )

      _a							:       Optional[Any]       					=			model.init_cache(input_ids.shape[0]		,    __UpperCamelCase   )
      _a							:       Optional[Any]       					=			jnp.ones((input_ids.shape[0], max_decoder_length)		,    dtype="""i4"""   )

      _a							:       List[str]       					=			jnp.broadcast_to(
          jnp.arange(input_ids.shape[-1] - 1   )[None, :]		,    (input_ids.shape[0], input_ids.shape[-1] - 1)   )
      _a							:       Optional[Any]       					=			model(
          input_ids[:, :-1]		,    attention_mask=__UpperCamelCase		,    past_key_values=__UpperCamelCase		,    position_ids=__UpperCamelCase		,    )

      _a							:       List[Any]       					=			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]		,    dtype="""i4"""   )
      _a							:       List[str]       					=			model(
          input_ids[:, -1:]		,    attention_mask=__UpperCamelCase		,    past_key_values=outputs_cache.past_key_values		,    position_ids=__UpperCamelCase		,    )

      _a							:       Optional[Any]       					=			model(__UpperCamelCase   )

      _a							:       str       					=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
      self.parent.assertTrue(diff < 1e-3		,    msg=f'''Max diff is {diff}'''   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			20
      _a							:       int       					=			model_class_name(__UpperCamelCase   )

      _a							:       Tuple       					=			jnp.concatenate(
          [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])   )]		,    axis=-1		,    )

      _a							:       Any       					=			model.init_cache(input_ids.shape[0]		,    __UpperCamelCase   )
      _a							:       Tuple       					=			jnp.broadcast_to(
          jnp.arange(input_ids.shape[-1] - 1   )[None, :]		,    (input_ids.shape[0], input_ids.shape[-1] - 1)   )

      _a							:       List[Any]       					=			model(
          input_ids[:, :-1]		,    attention_mask=__UpperCamelCase		,    past_key_values=__UpperCamelCase		,    position_ids=__UpperCamelCase		,    )
      _a							:       List[str]       					=			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]		,    dtype="""i4"""   )
      _a							:       Any       					=			model(
          input_ids[:, -1:]		,    past_key_values=outputs_cache.past_key_values		,    attention_mask=__UpperCamelCase		,    position_ids=__UpperCamelCase		,    )

      _a							:       List[str]       					=			model(__UpperCamelCase		,    attention_mask=__UpperCamelCase   )
      _a							:       Optional[int]       					=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
      self.parent.assertTrue(diff < 1e-3		,    msg=f'''Max diff is {diff}'''   )






@require_sentencepiece
@require_flax
class     UpperCamelCase					(  UpperCAmelCase_			,		UpperCAmelCase_			,		unittest.TestCase					):
  a    :str      					=				(FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else ()
  a    :List[str]      					=				(FlaxXGLMForCausalLM,) if is_flax_available() else ()



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			FlaxXGLMModelTester(self   )



  def 						a_       ( self   ):







      '''simple docstring'''


      for model_class_name in self.all_model_classes:
          _a					,   _a					,   _a							:       Optional[int]       					=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.check_use_cache_forward(__UpperCamelCase		,    __UpperCamelCase		,    __UpperCamelCase		,    __UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      for model_class_name in self.all_model_classes:
          _a					,   _a					,   _a							:       List[str]       					=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.check_use_cache_forward_with_attn_mask(
              __UpperCamelCase		,    __UpperCamelCase		,    __UpperCamelCase		,    __UpperCamelCase   )



  @slow
  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			XGLMTokenizer.from_pretrained("""XGLM"""		,    padding_side="""left"""   )
      _a							:       Dict       					=			tokenizer(["""Hello this is a long string""", """Hey"""]		,    return_tensors="""np"""		,    padding=__UpperCamelCase		,    truncation=__UpperCamelCase   )

      _a							:       int       					=			FlaxXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""   )
      _a							:       List[str]       					=			1
      _a							:       Union[str, Any]       					=			False

      _a							:       Dict       					=			jax.jit(model.generate   )

      _a							:       Optional[int]       					=			jit_generate(inputs["""input_ids"""]		,    attention_mask=inputs["""attention_mask"""]   ).sequences

      _a							:       List[str]       					=			tokenizer.batch_decode(__UpperCamelCase		,    skip_special_tokens=__UpperCamelCase   )

      _a							:       Optional[Any]       					=			[
          """Hello this is a long string of questions, but I'm not sure if I'm""",
          """Hey, I'm a newbie to the forum and I'""",
      ]

      self.assertListEqual(__UpperCamelCase		,    __UpperCamelCase   )



  @is_pt_flax_cross_test
  def 						a_       ( self   ):







      '''simple docstring'''


      _a					,   _a							:       int       					=			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          with self.subTest(model_class.__name__   ):
              # prepare inputs
              _a							:       Dict       					=			self._prepare_for_class(__UpperCamelCase		,    __UpperCamelCase   )
              _a							:       List[str]       					=			{k: torch.tensor(v.tolist()   ) for k, v in prepared_inputs_dict.items()}

              # load corresponding PyTorch class
              _a							:       int       					=			model_class.__name__[4:]  # Skip the "Flax" at the beginning
              _a							:       List[Any]       					=			getattr(__UpperCamelCase		,    __UpperCamelCase   )

              _a					,   _a							:       Dict       					=			pt_inputs["""input_ids"""].shape
              _a							:       Optional[Any]       					=			np.random.randint(0		,    seq_length - 1		,    size=(batch_size,)   )
              for batch_idx, start_index in enumerate(__UpperCamelCase   ):
                  _a							:       List[str]       					=			0
                  _a							:       str       					=			1
                  _a							:       List[Any]       					=			0
                  _a							:       Union[str, Any]       					=			1
              _a							:       Any       					=			pt_model_class(__UpperCamelCase   ).eval()
              # Flax models don't use the `use_cache` option and cache is not returned as a default.
              # So we disable `use_cache` here for PyTorch model.
              _a							:       Optional[Any]       					=			False
              _a							:       Optional[Any]       					=			model_class(__UpperCamelCase		,    dtype=jnp.floataa   )
              _a							:       str       					=			convert_pytorch_state_dict_to_flax(pt_model.state_dict()		,    __UpperCamelCase   )
              _a							:       Dict       					=			fx_state

              with torch.no_grad():
                  _a							:       str       					=			pt_model(**__UpperCamelCase   ).to_tuple()

              _a							:       List[Any]       					=			fx_model(**__UpperCamelCase   ).to_tuple()
              self.assertEqual(len(__UpperCamelCase   )		,    len(__UpperCamelCase   )		,    """Output lengths differ between Flax and PyTorch"""   )
              for fx_output, pt_output in zip(__UpperCamelCase		,    __UpperCamelCase   ):
                  self.assert_almost_equals(fx_output[:, -1]		,    pt_output[:, -1].numpy()		,    4e-2   )

              with tempfile.TemporaryDirectory() as tmpdirname:
                  pt_model.save_pretrained(__UpperCamelCase   )
                  _a							:       List[str]       					=			model_class.from_pretrained(__UpperCamelCase		,    from_pt=__UpperCamelCase   )

              _a							:       Optional[Any]       					=			fx_model_loaded(**__UpperCamelCase   ).to_tuple()
              self.assertEqual(
                  len(__UpperCamelCase   )		,    len(__UpperCamelCase   )		,    """Output lengths differ between Flax and PyTorch"""   )
              for fx_output_loaded, pt_output in zip(__UpperCamelCase		,    __UpperCamelCase   ):
                  self.assert_almost_equals(fx_output_loaded[:, -1]		,    pt_output[:, -1].numpy()		,    4e-2   )



  @is_pt_flax_cross_test
  def 						a_       ( self   ):







      '''simple docstring'''


      _a					,   _a							:       Optional[int]       					=			self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
          with self.subTest(model_class.__name__   ):
              # prepare inputs
              _a							:       Union[str, Any]       					=			self._prepare_for_class(__UpperCamelCase		,    __UpperCamelCase   )
              _a							:       int       					=			{k: torch.tensor(v.tolist()   ) for k, v in prepared_inputs_dict.items()}

              # load corresponding PyTorch class
              _a							:       int       					=			model_class.__name__[4:]  # Skip the "Flax" at the beginning
              _a							:       Tuple       					=			getattr(__UpperCamelCase		,    __UpperCamelCase   )

              _a							:       List[Any]       					=			pt_model_class(__UpperCamelCase   ).eval()
              _a							:       Optional[Any]       					=			False
              _a							:       str       					=			model_class(__UpperCamelCase		,    dtype=jnp.floataa   )

              _a							:       Tuple       					=			load_flax_weights_in_pytorch_model(__UpperCamelCase		,    fx_model.params   )
              _a					,   _a							:       Union[str, Any]       					=			pt_inputs["""input_ids"""].shape
              _a							:       int       					=			np.random.randint(0		,    seq_length - 1		,    size=(batch_size,)   )
              for batch_idx, start_index in enumerate(__UpperCamelCase   ):
                  _a							:       Tuple       					=			0
                  _a							:       str       					=			1
                  _a							:       Optional[int]       					=			0
                  _a							:       List[Any]       					=			1

              # make sure weights are tied in PyTorch
              pt_model.tie_weights()

              with torch.no_grad():
                  _a							:       Optional[Any]       					=			pt_model(**__UpperCamelCase   ).to_tuple()

              _a							:       Any       					=			fx_model(**__UpperCamelCase   ).to_tuple()
              self.assertEqual(len(__UpperCamelCase   )		,    len(__UpperCamelCase   )		,    """Output lengths differ between Flax and PyTorch"""   )
              for fx_output, pt_output in zip(__UpperCamelCase		,    __UpperCamelCase   ):
                  self.assert_almost_equals(fx_output[:, -1]		,    pt_output[:, -1].numpy()		,    4e-2   )

              with tempfile.TemporaryDirectory() as tmpdirname:
                  fx_model.save_pretrained(__UpperCamelCase   )
                  _a							:       Dict       					=			pt_model_class.from_pretrained(__UpperCamelCase		,    from_flax=__UpperCamelCase   )

              with torch.no_grad():
                  _a							:       List[Any]       					=			pt_model_loaded(**__UpperCamelCase   ).to_tuple()

              self.assertEqual(
                  len(__UpperCamelCase   )		,    len(__UpperCamelCase   )		,    """Output lengths differ between Flax and PyTorch"""   )
              for fx_output, pt_output in zip(__UpperCamelCase		,    __UpperCamelCase   ):
                  self.assert_almost_equals(fx_output[:, -1]		,    pt_output[:, -1].numpy()		,    4e-2   )



  @slow
  def 						a_       ( self   ):







      '''simple docstring'''


      for model_class_name in self.all_model_classes:
          _a							:       Dict       					=			model_class_name.from_pretrained("""facebook/xglm-564M"""   )
          _a							:       Dict       					=			model(np.ones((1, 1)   )   )
          self.assertIsNotNone(__UpperCamelCase   )












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


