




'''simple docstring'''





import argparse
import collections

import jax
import jax.numpy as jnp
import torch
import torch.nn as nn
from clip.model import CLIP
from flax.training import checkpoints
from huggingface_hub import Repository

from transformers import (
    CLIPTokenizer,
    OwlViTConfig,
    OwlViTForObjectDetection,
    OwlViTImageProcessor,
    OwlViTModel,
    OwlViTProcessor,
)


a		:  Any   			=			{
    '''vit_b32''': {
        '''embed_dim''': 5_1_2,
        '''image_resolution''': 7_6_8,
        '''context_length''': 1_6,
        '''vocab_size''': 4_9_4_0_8,
        '''vision_layers''': 1_2,
        '''vision_width''': 7_6_8,
        '''vision_patch_size''': 3_2,
        '''transformer_width''': 5_1_2,
        '''transformer_heads''': 8,
        '''transformer_layers''': 1_2,
    },
    '''vit_b16''': {
        '''embed_dim''': 5_1_2,
        '''image_resolution''': 7_6_8,
        '''context_length''': 1_6,
        '''vocab_size''': 4_9_4_0_8,
        '''vision_layers''': 1_2,
        '''vision_width''': 7_6_8,
        '''vision_patch_size''': 1_6,
        '''transformer_width''': 5_1_2,
        '''transformer_heads''': 8,
        '''transformer_layers''': 1_2,
    },
    '''vit_l14''': {
        '''embed_dim''': 7_6_8,
        '''image_resolution''': 8_4_0,
        '''context_length''': 1_6,
        '''vocab_size''': 4_9_4_0_8,
        '''vision_layers''': 2_4,
        '''vision_width''': 1_0_2_4,
        '''vision_patch_size''': 1_4,
        '''transformer_width''': 7_6_8,
        '''transformer_heads''': 1_2,
        '''transformer_layers''': 1_2,
    },
}





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_=""      ,  UpperCAmelCase_="/"	):
    _a							:       str       					=			[]

    for k, v in params.items():
        _a							:       Union[str, Any]       					=			parent_key + sep + k if parent_key else k

        if isinstance(UpperCAmelCase_      ,  collections.MutableMapping	):
            items.extend(flatten_nested_dict(UpperCAmelCase_      ,  UpperCAmelCase_      ,  sep=UpperCAmelCase_	).items()	)
        else:
            items.append((new_key, v)	)
    return dict(UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_	):
    return jax.tree_util.tree_map(lambda UpperCAmelCase_	: x.astype(jnp.floataa	) if x.dtype == jnp.bfloataa else x      ,  UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    _a					,   _a					,   _a							:       str       					=			pt_attn_layer.in_proj_weight.chunk(3      ,  dim=0	)
    _a					,   _a					,   _a							:       Dict       					=			pt_attn_layer.in_proj_bias.chunk(3      ,  dim=0	)

    _a							:       Tuple       					=			pt_attn_layer.out_proj.weight
    _a							:       str       					=			pt_attn_layer.out_proj.bias

    _a							:       Tuple       					=			q_proj
    _a							:       int       					=			q_proj_bias

    _a							:       Any       					=			k_proj
    _a							:       List[str]       					=			k_proj_bias

    _a							:       str       					=			v_proj
    _a							:       Optional[int]       					=			v_proj_bias

    _a							:       Dict       					=			out_proj_weights
    _a							:       Any       					=			out_proj_bias





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    copy_linear(hf_mlp.fca      ,  pt_mlp.c_fc	)
    copy_linear(hf_mlp.fca      ,  pt_mlp.c_proj	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    _a							:       Dict       					=			pt_linear.weight
    _a							:       Optional[Any]       					=			pt_linear.bias





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    # copy layer norms
    copy_linear(hf_layer.layer_norma      ,  pt_layer.ln_a	)
    copy_linear(hf_layer.layer_norma      ,  pt_layer.ln_a	)

    # copy MLP
    copy_mlp(hf_layer.mlp      ,  pt_layer.mlp	)

    # copy attn
    copy_attn_layer(hf_layer.self_attn      ,  pt_layer.attn	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    for hf_layer, pt_layer in zip(UpperCAmelCase_      ,  UpperCAmelCase_	):
        copy_layer(UpperCAmelCase_      ,  UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    # copy  embeds
    _a							:       Optional[Any]       					=			pt_model.token_embedding.weight
    _a							:       str       					=			pt_model.positional_embedding

    # copy layer norm
    copy_linear(hf_encoder.final_layer_norm      ,  pt_model.ln_final	)

    # copy hidden layers
    copy_layers(hf_encoder.encoder.layers      ,  pt_model.transformer.resblocks	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    # copy projection
    _a							:       List[str]       					=			pt_model.text_projection.data.T

    # copy text encoder
    copy_encoder(hf_model.text_model      ,  UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    # copy projection
    _a							:       Any       					=			pt_model.visual.proj.data.T

    # copy layer norms
    copy_linear(hf_model.vision_model.pre_layernorm      ,  pt_model.visual.ln_pre	)
    copy_linear(hf_model.vision_model.post_layernorm      ,  pt_model.visual.ln_post	)

    # copy embeds
    _a							:       Dict       					=			pt_model.visual.conva.weight.data
    _a							:       Dict       					=			pt_model.visual.class_embedding
    _a							:       Optional[int]       					=			pt_model.visual.positional_embedding.data

    # copy encoder
    copy_layers(hf_model.vision_model.encoder.layers      ,  pt_model.visual.transformer.resblocks	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    _a							:       Optional[Any]       					=			flatten_nested_dict(flax_params["""backbone"""]["""merged_class_token"""]	)

    _a							:       Tuple       					=			torch.from_numpy(flax_class_token_params["""scale"""]	)
    _a							:       Any       					=			torch.from_numpy(flax_class_token_params["""bias"""]	)
    _a							:       Any       					=			nn.Parameter(UpperCAmelCase_	)
    _a							:       int       					=			nn.Parameter(UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    _a							:       Any       					=			hf_model.state_dict()
    _a							:       Optional[int]       					=			{}

    # Rename class prediction head flax params to pytorch HF
    _a							:       Optional[int]       					=			flatten_nested_dict(flax_params["""class_head"""]	)

    for flax_key, v in flax_class_params.items():
        _a							:       List[str]       					=			flax_key.replace("""/"""      ,  """."""	)
        _a							:       str       					=			torch_key.replace(""".kernel"""      ,  """.weight"""	)
        _a							:       Optional[int]       					=			torch_key.replace("""Dense_0"""      ,  """dense0"""	)
        _a							:       str       					=			"""class_head.""" + torch_key

        if "weight" in torch_key and v.ndim == 2:
            _a							:       Optional[int]       					=			v.T

        _a							:       Optional[Any]       					=			nn.Parameter(torch.from_numpy(UpperCAmelCase_	)	)

    # Rename box prediction box flax params to pytorch HF
    _a							:       int       					=			flatten_nested_dict(flax_params["""obj_box_head"""]	)

    for flax_key, v in flax_box_params.items():
        _a							:       Optional[int]       					=			flax_key.replace("""/"""      ,  """."""	)
        _a							:       Any       					=			torch_key.replace(""".kernel"""      ,  """.weight"""	)
        _a							:       Optional[Any]       					=			torch_key.replace("""_"""      ,  """"""	).lower()
        _a							:       Dict       					=			"""box_head.""" + torch_key

        if "weight" in torch_key and v.ndim == 2:
            _a							:       Union[str, Any]       					=			v.T

        _a							:       Any       					=			nn.Parameter(torch.from_numpy(UpperCAmelCase_	)	)

    # Copy flax params to PyTorch params
    for name, param in new_params.items():
        if name in pt_params.keys():
            pt_params[name].copy_(UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    for k, v in flax_attn_params.items():
        if k.startswith("""transformer"""	):
            _a							:       Any       					=			k.replace("""transformer.resblocks"""      ,  """text_model.encoder.layers"""	)
        else:
            _a							:       Optional[Any]       					=			k.replace("""visual.transformer.resblocks"""      ,  """vision_model.encoder.layers"""	)

        _a							:       str       					=			torch_key.replace("""attn"""      ,  """self_attn"""	)
        _a							:       Any       					=			torch_key.replace("""key"""      ,  """k_proj"""	)
        _a							:       Any       					=			torch_key.replace("""value"""      ,  """v_proj"""	)
        _a							:       int       					=			torch_key.replace("""query"""      ,  """q_proj"""	)
        _a							:       int       					=			torch_key.replace("""out"""      ,  """out_proj"""	)

        if "bias" in torch_key and v.ndim == 2:
            _a							:       int       					=			v.shape[0] * v.shape[1]
            _a							:       Optional[int]       					=			v.reshape(UpperCAmelCase_	)

        if "weight" in torch_key and "out" in torch_key:
            _a							:       Optional[Any]       					=			(v.shape[0] * v.shape[1], v.shape[2])
            _a							:       Optional[int]       					=			v.reshape(UpperCAmelCase_	).T

        if "weight" in torch_key and "out" not in torch_key:
            _a							:       int       					=			(v.shape[0], v.shape[1] * v.shape[2])
            _a							:       Optional[Any]       					=			v.reshape(UpperCAmelCase_	).T

        # Copy flax CLIP attn params to HF PyTorch params
        _a							:       List[str]       					=			torch.from_numpy(UpperCAmelCase_	)
        hf_backbone.state_dict()[torch_key].copy_(UpperCAmelCase_	)





def UpperCAmelCase						(					UpperCAmelCase_	):
    _a							:       List[str]       					=			{}
    _a							:       Optional[Any]       					=			[]

    for k, v in params.items():
        if "attn." in k:
            _a							:       Dict       					=			k[: k.rindex("""attn."""	) + 5]
            if base in processed_attn_layers:
                continue

            processed_attn_layers.append(UpperCAmelCase_	)
            _a							:       List[str]       					=			params[base + """out.weight"""].shape[-1]
            _a							:       str       					=			params[base + """out.weight"""].reshape(UpperCAmelCase_      ,  UpperCAmelCase_	).T
            _a							:       Any       					=			params[base + """out.bias"""]
        else:
            _a							:       Dict       					=			v
    return new_params





def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_	):
    _a							:       int       					=			CLIP(**UpperCAmelCase_	)
    torch_model.eval()
    _a							:       Dict       					=			torch_model.state_dict()

    _a							:       str       					=			flatten_nested_dict(flax_params["""backbone"""]["""clip"""]	)
    _a							:       Optional[int]       					=			{}

    for flax_key, v in flax_clip_params.items():
        _a							:       Dict       					=			flax_key.replace("""/"""      ,  """."""	)
        _a							:       int       					=			torch_key.replace("""text.token_embedding.embedding"""      ,  """token_embedding.kernel"""	)

        if (
            torch_key.startswith("""text.transformer"""	)
            or torch_key.startswith("""text.text_projection"""	)
            or torch_key.startswith("""text.ln_final"""	)
            or torch_key.startswith("""text.positional_embedding"""	)
        ):
            _a							:       str       					=			torch_key[5:]

        _a							:       Any       					=			torch_key.replace("""text_projection.kernel"""      ,  """text_projection"""	)
        _a							:       List[str]       					=			torch_key.replace("""visual.proj.kernel"""      ,  """visual.proj"""	)
        _a							:       Dict       					=			torch_key.replace(""".scale"""      ,  """.weight"""	)
        _a							:       str       					=			torch_key.replace(""".kernel"""      ,  """.weight"""	)

        if "conv" in torch_key or "downsample.0.weight" in torch_key:
            _a							:       Optional[int]       					=			v.transpose(3      ,  2      ,  0      ,  1	)

        elif "weight" in torch_key and v.ndim == 2 and "embedding" not in torch_key:
            # Fully connected layers are transposed, embeddings are not
            _a							:       List[str]       					=			v.T

        _a							:       Union[str, Any]       					=			v

    _a							:       str       					=			_convert_attn_layers(UpperCAmelCase_	)
    new_torch_params.update(UpperCAmelCase_	)
    _a							:       str       					=			{}

    # Copy flax CLIP backbone params to PyTorch params
    for name, param in new_torch_params.items():
        if name in torch_clip_params.keys():
            _a							:       str       					=			torch.from_numpy(new_torch_params[name]	)
            torch_clip_params[name].copy_(UpperCAmelCase_	)
        else:
            _a							:       List[Any]       					=			param

    return torch_clip_params, torch_model, attn_params





@torch.no_grad()
def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_      ,  UpperCAmelCase_      ,  UpperCAmelCase_      ,  UpperCAmelCase_=None	):
    _a							:       Tuple       					=			Repository(UpperCAmelCase_      ,  clone_from=F'''google/{pytorch_dump_folder_path}'''	)
    repo.git_pull()

    if config_path is not None:
        _a							:       Optional[Any]       					=			OwlViTConfig.from_pretrained(UpperCAmelCase_	)
    else:
        _a							:       Any       					=			OwlViTConfig()

    _a							:       List[str]       					=			OwlViTModel(UpperCAmelCase_	).eval()
    _a							:       Any       					=			OwlViTForObjectDetection(UpperCAmelCase_	).eval()

    copy_text_model_and_projection(UpperCAmelCase_      ,  UpperCAmelCase_	)
    copy_vision_model_and_projection(UpperCAmelCase_      ,  UpperCAmelCase_	)
    _a							:       int       					=			pt_backbone.logit_scale
    copy_flax_attn_params(UpperCAmelCase_      ,  UpperCAmelCase_	)

    _a							:       Any       					=			hf_backbone
    copy_class_merge_token(UpperCAmelCase_      ,  UpperCAmelCase_	)
    copy_class_box_heads(UpperCAmelCase_      ,  UpperCAmelCase_	)

    # Save HF model
    hf_model.save_pretrained(repo.local_dir	)

    # Initialize image processor
    _a							:       List[str]       					=			OwlViTImageProcessor(
        size=config.vision_config.image_size      ,  crop_size=config.vision_config.image_size	)
    # Initialize tokenizer
    _a							:       List[str]       					=			CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32"""      ,  pad_token="""!"""      ,  model_max_length=16	)

    # Initialize processor
    _a							:       List[str]       					=			OwlViTProcessor(image_processor=UpperCAmelCase_      ,  tokenizer=UpperCAmelCase_	)
    image_processor.save_pretrained(repo.local_dir	)
    processor.save_pretrained(repo.local_dir	)

    repo.git_add()
    repo.git_commit("""Upload model and processor"""	)
    repo.git_push()


if __name__ == "__main__":
  a		:  List[Any]   			=			argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--owlvit_version''',
      default=None,
      type=str,
      required=True,
      help='''OWL-ViT model name [clip_b16, clip_b32, clip_l14].''',
  )
  parser.add_argument(
      '''--owlvit_checkpoint''', default=None, type=str, required=True, help='''Path to flax model checkpoint.'''
  )
  parser.add_argument('''--hf_config''', default=None, type=str, required=True, help='''Path to HF model config.''')
  parser.add_argument(
      '''--pytorch_dump_folder_path''', default='''hf_model''', type=str, help='''Path to the output PyTorch model.'''
  )
  a		:  Any   			=			parser.parse_args()

  # Initialize PyToch clip model
  a		:  str   			=			args.owlvit_version
  if model_name == "clip_b16":
    a		:  int   			=			CONFIGS['''vit_b16''']
  elif model_name == "clip_b32":
    a		:  Optional[Any]   			=			CONFIGS['''vit_b32''']
  elif model_name == "clip_l14":
    a		:  Union[str, Any]   			=			CONFIGS['''vit_l14''']

  # Load from checkpoint and convert params to float-32
  a		:  Any   			=			checkpoints.restore_checkpoint(args.owlvit_checkpoint, target=None)['''optimizer''']['''target''']
  a		:  str   			=			jax.tree_util.tree_map(lambda x: x.astype(jnp.floataa) if x.dtype == jnp.bfloataa else x, variables)
  del variables

  # Convert CLIP backbone
  a			,							a			,							a		:  Optional[Any]   			=			convert_clip_backbone(flax_params, torch_config)

  convert_owlvit_checkpoint(clip_pt, flax_params, attn_params, args.pytorch_dump_folder_path, args.hf_config)








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


