



from ...configuration_utils import PretrainedConfig
from ...utils import logging


A__  :  Optional[int]       = logging.get_logger(__name__)

A__  :  Dict       = {
    # pcqm4mv1 now deprecated
    '''graphormer-base''': '''https://huggingface.co/clefourrier/graphormer-base-pcqm4mv2/resolve/main/config.json''',
    # See all Graphormer models at https://huggingface.co/models?filter=graphormer
}



class     __snake_case						(					UpperCamelCase_						):
							_a      				=			'''graphormer'''
							_a      				=			['''past_key_values''']




							def __init__(	self					:	List[str]    ,    A_					:	int = 1    ,    A_					:	int = 5_1_2 * 9    ,    A_					:	int = 5_1_2 * 3    ,    A_					:	int = 5_1_2    ,    A_					:	int = 5_1_2    ,    A_					:	int = 5_1_2    ,    A_					:	int = 1_2_8    ,    A_					:	int = 5    ,    A_					:	int = 1_0_2_4    ,    A_					:	str = "multi_hop"    ,    A_					:	int = 5_1_2    ,    A_					:	bool = False    ,    A_					:	int = 1_2    ,    A_					:	int = 7_6_8    ,    A_					:	int = 7_6_8    ,    A_					:	int = 3_2    ,    A_					:	float = 0.1    ,    A_					:	float = 0.1    ,    A_					:	float = 0.0    ,    A_					:	bool = False    ,    A_					:	bool = False    ,    A_					:	bool = False    ,    A_					:	str = "gelu"    ,    A_					:	float = None    ,    A_					:	bool = False    ,    A_					:	int = 0    ,    A_					:	bool = False    ,    A_					:	float = 0.0    ,    A_					:	int = 8    ,    A_					:	int = None    ,    A_					:	int = None    ,    A_					:	bool = True    ,    A_					:	bool = True    ,    A_					:	Optional[int]=0    ,    A_					:	Optional[Any]=1    ,    A_					:	int=2    ,    **A_					:	Optional[Any]    ,    ):
									lowerCAmelCase_      :					Union[str, Any]     =			num_classes
									lowerCAmelCase_      :					List[str]     =			num_atoms
									lowerCAmelCase_      :					Any     =			num_in_degree
									lowerCAmelCase_      :					str     =			num_out_degree
									lowerCAmelCase_      :					Tuple     =			num_edges
									lowerCAmelCase_      :					Any     =			num_spatial
									lowerCAmelCase_      :					List[str]     =			num_edge_dis
									lowerCAmelCase_      :					int     =			edge_type
									lowerCAmelCase_      :					Optional[Any]     =			multi_hop_max_dist
									lowerCAmelCase_      :					Tuple     =			spatial_pos_max
									lowerCAmelCase_      :					List[str]     =			max_nodes
									lowerCAmelCase_      :					str     =			num_hidden_layers
									lowerCAmelCase_      :					Optional[Any]     =			embedding_dim
									lowerCAmelCase_      :					Optional[Any]     =			embedding_dim
									lowerCAmelCase_      :					str     =			ffn_embedding_dim
									lowerCAmelCase_      :					Union[str, Any]     =			num_attention_heads
									lowerCAmelCase_      :					Tuple     =			dropout
									lowerCAmelCase_      :					Optional[int]     =			attention_dropout
									lowerCAmelCase_      :					str     =			layerdrop
									lowerCAmelCase_      :					Union[str, Any]     =			encoder_normalize_before
									lowerCAmelCase_      :					Union[str, Any]     =			pre_layernorm
									lowerCAmelCase_      :					str     =			apply_graphormer_init
									lowerCAmelCase_      :					int     =			activation_fn
									lowerCAmelCase_      :					Union[str, Any]     =			embed_scale
									lowerCAmelCase_      :					Tuple     =			freeze_embeddings
									lowerCAmelCase_      :					Tuple     =			num_trans_layers_to_freeze
									lowerCAmelCase_      :					Tuple     =			share_input_output_embed
									lowerCAmelCase_      :					Tuple     =			traceable
									lowerCAmelCase_      :					List[Any]     =			q_noise
									lowerCAmelCase_      :					int     =			qn_block_size

									# These parameters are here for future extensions
									# atm, the model only supports self attention
									lowerCAmelCase_      :					Tuple     =			kdim
									lowerCAmelCase_      :					Any     =			vdim
									lowerCAmelCase_      :					List[Any]     =			self_attention
									lowerCAmelCase_      :					Optional[int]     =			bias

									super().__init__(
									    pad_token_id=A_    ,    bos_token_id=A_    ,    eos_token_id=A_    ,    **A_    ,    )










import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


A__  :  Tuple       = logging.get_logger(__name__)

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



class     __snake_case						(					UpperCamelCase_						):
							_a      				=			RetriBertConfig
							_a      				=			None
							_a      				=			'''retribert'''




							def        UpperCAmelCase__      (	self					:	Optional[int]    ,    A_					:	Union[str, Any]):
									if isinstance(A_    ,    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(A_    ,    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(A_    ,    nn.LayerNorm):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0)





A__  :  str       = R'''

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''



@add_start_docstrings(
    '''Bert Based model to embed queries or document for document retrieval.'''						,UpperCamelCase_						,)
class     __snake_case						(					UpperCamelCase_						):




							def __init__(	self					:	Optional[int]    ,    A_					:	RetriBertConfig):
									super().__init__(A_)
									lowerCAmelCase_      :					Optional[int]     =			config.projection_dim

									lowerCAmelCase_      :					int     =			BertModel(A_)
									lowerCAmelCase_      :					int     =			None if config.share_encoders else BertModel(A_)
									lowerCAmelCase_      :					str     =			nn.Dropout(config.hidden_dropout_prob)
									lowerCAmelCase_      :					Dict     =			nn.Linear(config.hidden_size    ,    config.projection_dim    ,    bias=A_)
									lowerCAmelCase_      :					Any     =			nn.Linear(config.hidden_size    ,    config.projection_dim    ,    bias=A_)

									lowerCAmelCase_      :					int     =			nn.CrossEntropyLoss(reduction='''mean''')

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




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

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

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




							def        UpperCAmelCase__      (	self					:	List[str]    ,    A_					:	List[Any]    ,    A_					:	Union[str, Any]=None    ,    A_					:	Dict=-1    ,    ):
									lowerCAmelCase_      :					Optional[int]     =			self.embed_sentences_checkpointed(
									    A_    ,    A_    ,    self.bert_query    ,    A_    ,    )
									return self.project_query(A_)




							def        UpperCAmelCase__      (	self					:	Optional[Any]    ,    A_					:	str    ,    A_					:	int=None    ,    A_					:	Any=-1    ,    ):
									lowerCAmelCase_      :					Union[str, Any]     =			self.embed_sentences_checkpointed(
									    A_    ,    A_    ,    self.bert_query if self.bert_doc is None else self.bert_doc    ,    A_    ,    )
									return self.project_doc(A_)







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





