
import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
A__  :  Tuple       = "\\n@InProceedings{huggingface:dataset,\ntitle = {A great new dataset},\nauthor={huggingface, Inc.\n},\nyear={2020}\n}\n"

# TODO: Add description of the dataset here
# You can copy an official description
A__  :  Union[str, Any]       = "\\nThis new dataset is designed to solve this great NLP task and is crafted with a lot of care.\n"

# TODO: Add a link to an official homepage for the dataset here
A__  :  int       = ""

# TODO: Add the licence for the dataset here if you can find it
A__  :  str       = ""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
A__  :  Optional[int]       = {
    "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
    "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
}



class     __snake_case						(					datasets.GeneratorBasedBuilder						):
							_a      				=			datasets.Version('''1.1.0'''						)

							# This is an example of a dataset with multiple configurations.
							# If you don't want/need to define several sub-sets in your dataset,
							# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

							# If you need to make complex sub-parts in the datasets with configurable options
							# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
							# BUILDER_CONFIG_CLASS = MyBuilderConfig

							# You will be able to load one or the other configurations in the following list with
							# data = datasets.load_dataset('my_dataset', 'first_domain')
							# data = datasets.load_dataset('my_dataset', 'second_domain')
							_a      				=			[
							    datasets.BuilderConfig(name='''first_domain'''						,version=lowerCAmelCase_						,description='''This part of my dataset covers a first domain'''						),
							    datasets.BuilderConfig(name='''second_domain'''						,version=lowerCAmelCase_						,description='''This part of my dataset covers a second domain'''						),
							]

							_a      				=			'''first_domain'''  # It's not mandatory to have a default configuration. Just use one if it make sense.




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
									if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
											lowerCAmelCase_      :					Any     =			datasets.Features(
											    {
											        '''sentence''': datasets.Value('''string'''),
											        '''option1''': datasets.Value('''string'''),
											        '''answer''': datasets.Value('''string''')
											        # These are the features of your dataset like images, labels ...
											    })
									else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
											lowerCAmelCase_      :					Any     =			datasets.Features(
											    {
											        '''sentence''': datasets.Value('''string'''),
											        '''option2''': datasets.Value('''string'''),
											        '''second_domain_answer''': datasets.Value('''string''')
											        # These are the features of your dataset like images, labels ...
											    })
									return datasets.DatasetInfo(
									    # This is the description that will appear on the datasets page.
									    description=_DESCRIPTION    ,    features=_snake_case    ,    homepage=_HOMEPAGE    ,    license=_LICENSE    ,    citation=_CITATION    ,    )




							def        UpperCAmelCase__      (	self					:	List[Any]    ,    A_					:	Dict):
									# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
									# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

									# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
									# It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
									# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
									lowerCAmelCase_      :					Union[str, Any]     =			_URLS[self.config.name]
									lowerCAmelCase_      :					Optional[int]     =			dl_manager.download_and_extract(_snake_case)
									return [
									    datasets.SplitGenerator(
									        name=datasets.Split.TRAIN    ,    gen_kwargs={
									            '''filepath''': os.path.join(_snake_case    ,    '''train.jsonl'''),
									            '''split''': '''train''',
									        }    ,    ),
									    datasets.SplitGenerator(
									        name=datasets.Split.VALIDATION    ,    gen_kwargs={
									            '''filepath''': os.path.join(_snake_case    ,    '''dev.jsonl'''),
									            '''split''': '''dev''',
									        }    ,    ),
									    datasets.SplitGenerator(
									        name=datasets.Split.TEST    ,    gen_kwargs={
									            '''filepath''': os.path.join(_snake_case    ,    '''test.jsonl'''),
									            '''split''': '''test'''
									        }    ,    ),
									]







							def        UpperCAmelCase__      (	self					:	Optional[Any]    ,    A_					:	Any    ,    A_					:	Dict):
									# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
									# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
									with open(_snake_case    ,    encoding='''utf-8''') as f:
											for key, row in enumerate(_snake_case):
													lowerCAmelCase_      :					List[str]     =			json.loads(_snake_case)
													if self.config.name == "first_domain":
															# Yields examples as (key, example) tuples
															yield key, {
															    "sentence": data["sentence"],
															    "option1": data["option1"],
															    "answer": "" if split == "test" else data["answer"],
															}
													else:
															yield key, {
															    "sentence": data["sentence"],
															    "option2": data["option2"],
															    "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
															}










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





