






'''simple docstring'''





import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
	import bitsandbytes as bnb

from copy import deepcopy


a_							=    logging.getLogger(__name__)


def        _a  (     UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				List[Any]    ,   UpperCamelCase_					:				Optional[Any] = None    ,   UpperCamelCase_					:				Optional[int] = None    ,   UpperCamelCase_					:				List[str] = None    ,   UpperCamelCase_					:				List[str] = None    ,   UpperCamelCase_					:				Dict = None    ,   UpperCamelCase_					:				Union[str, Any] = False    ,   ) ->   List[Any]:
						"""simple docstring"""







						lowerCAmelCase__       =						bnb_quantization_config.load_in_abit
						lowerCAmelCase__       =						bnb_quantization_config.load_in_abit

						if load_in_abit and not is_abit_bnb_available():
												raise ImportError(
												    "You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"
												    " make sure you have the latest version of `bitsandbytes` installed."   )
						if load_in_abit and not is_abit_bnb_available():
												raise ValueError(
												    "You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"
												    "make sure you have the latest version of `bitsandbytes` installed."   )

						lowerCAmelCase__       =						[]
						# custom device map
						if isinstance(UpperCamelCase_    ,   UpperCamelCase_   ) and len(device_map.keys()   ) > 1:
												lowerCAmelCase__       =						[key for key, value in device_map.items() if value in ['''disk''', '''cpu''']]

						# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
						if bnb_quantization_config.skip_modules is None:
												lowerCAmelCase__       =						get_keys_to_not_convert(UpperCamelCase_   )

						# add cpu modules to skip modules only for 4-bit modules
						if load_in_abit:
												bnb_quantization_config.skip_modules.extend(UpperCamelCase_   )
						lowerCAmelCase__       =						bnb_quantization_config.skip_modules

						# We add the modules we want to keep in full precision
						if bnb_quantization_config.keep_in_fpaa_modules is None:
												lowerCAmelCase__       =						[]
						lowerCAmelCase__       =						bnb_quantization_config.keep_in_fpaa_modules
						modules_to_not_convert.extend(UpperCamelCase_   )

						# compatibility with peft
						lowerCAmelCase__       =						load_in_abit
						lowerCAmelCase__       =						load_in_abit

						lowerCAmelCase__       =						get_parameter_device(UpperCamelCase_   )
						if model_device.type != "meta":
												# quantization of an already loaded model
												logger.warning(
												    "It is not recommended to quantize a loaded model. "
												    "The model should be instantiated under the `init_empty_weights` context manager."   )
												lowerCAmelCase__       =						replace_with_bnb_layers(UpperCamelCase_    ,   UpperCamelCase_    ,   modules_to_not_convert=UpperCamelCase_   )
												# convert param to the right dtype
												lowerCAmelCase__       =						bnb_quantization_config.torch_dtype
												for name, param in model.state_dict().items():
																		if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules   ):
																								param.to(torch.floataa   )
																								if param.dtype != torch.floataa:
																														lowerCAmelCase__       =						name.replace(".weight"    ,   ""   ).replace(".bias"    ,   ""   )
																														lowerCAmelCase__       =						getattr(UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_   )
																														if param is not None:
																																				param.to(torch.floataa   )
																		elif torch.is_floating_point(UpperCamelCase_   ):
																								param.to(UpperCamelCase_   )
												if model_device.type == "cuda":
																		# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
																		model.cuda(torch.cuda.current_device()   )
																		torch.cuda.empty_cache()
												elif torch.cuda.is_available():
																		model.to(torch.cuda.current_device()   )
												else:
																		raise RuntimeError("No GPU found. A GPU is needed for quantization."   )
												logger.info(
												    F"The model device type is {model_device.type}. However, cuda is needed for quantization."
												    "We move the model to cuda."   )
												return model

						elif weights_location is None:
												raise RuntimeError(
												    F"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} "   )

						else:
												with init_empty_weights():
																		lowerCAmelCase__       =						replace_with_bnb_layers(
																		    UpperCamelCase_    ,   UpperCamelCase_    ,   modules_to_not_convert=UpperCamelCase_   )

												lowerCAmelCase__       =						get_quantized_model_device_map(
												    UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   max_memory=UpperCamelCase_    ,   no_split_module_classes=UpperCamelCase_    ,   )
												if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
																		lowerCAmelCase__       =						True

												lowerCAmelCase__       =						any(x in list(device_map.values()   ) for x in ["cpu", "disk"]   )

												load_checkpoint_in_model(
												    UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   dtype=bnb_quantization_config.torch_dtype    ,   offload_folder=UpperCamelCase_    ,   offload_state_dict=UpperCamelCase_    ,   keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules    ,   offload_abit_bnb=load_in_abit and offload    ,   )
												return dispatch_model(UpperCamelCase_    ,   device_map=UpperCamelCase_    ,   offload_dir=UpperCamelCase_   )


def        _a  (     UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				Union[str, Any]    ,   UpperCamelCase_					:				Any=None    ,   UpperCamelCase_					:				Tuple=None    ,   UpperCamelCase_					:				Union[str, Any]=None   ) ->   Union[str, Any]:
						"""simple docstring"""







						if device_map is None:
												if torch.cuda.is_available():
																		lowerCAmelCase__       =						{'''''': torch.cuda.current_device()}
												else:
																		raise RuntimeError("No GPU found. A GPU is needed for quantization."   )
												logger.info("The device_map was not initialized." "Setting device_map to `{\'\':torch.cuda.current_device()}`."   )

						if isinstance(UpperCamelCase_    ,   UpperCamelCase_   ):
												if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
																		raise ValueError(
																		    "If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or "
																		    "\'sequential\'."   )

												lowerCAmelCase__       =						{}
												special_dtypes.update(
												    {
												        name: bnb_quantization_config.torch_dtype
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.skip_modules   )
												    }   )
												special_dtypes.update(
												    {
												        name: torch.floataa
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules   )
												    }   )

												lowerCAmelCase__       =						{}
												lowerCAmelCase__       =						special_dtypes
												lowerCAmelCase__       =						no_split_module_classes
												lowerCAmelCase__       =						bnb_quantization_config.target_dtype

												# get max_memory for each device.
												if device_map != "sequential":
																		lowerCAmelCase__       =						get_balanced_memory(
																		    UpperCamelCase_    ,   low_zero=(device_map == "balanced_low_0")    ,   max_memory=UpperCamelCase_    ,   **UpperCamelCase_    ,   )

												lowerCAmelCase__       =						max_memory
												lowerCAmelCase__       =						infer_auto_device_map(UpperCamelCase_    ,   **UpperCamelCase_   )

						if isinstance(UpperCamelCase_    ,   UpperCamelCase_   ):
												# check if don't have any quantized module on the cpu
												lowerCAmelCase__       =						bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

												lowerCAmelCase__       =						{
												    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
												}
												for device in ["cpu", "disk"]:
																		if device in device_map_without_some_modules.values():
																								if bnb_quantization_config.load_in_abit:
																														raise ValueError(
																														    "\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        "   )
																								else:
																														logger.info(
																														    "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit"   )
												del device_map_without_some_modules
						return device_map


def        _a  (     UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				List[str]=None    ,   UpperCamelCase_					:				Dict=None   ) ->   Union[str, Any]:
						"""simple docstring"""







						if modules_to_not_convert is None:
												lowerCAmelCase__       =						[]

						lowerCAmelCase__       =						_replace_with_bnb_layers(
						    UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_   )
						if not has_been_replaced:
												logger.warning(
												    "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
												    " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."
												    " Please double check your model architecture, or submit an issue on github if you think this is"
												    " a bug."   )
						return model


def        _a  (     UpperCamelCase_					:				Any    ,   UpperCamelCase_					:				Optional[int]    ,   UpperCamelCase_					:				int=None    ,   UpperCamelCase_					:				Optional[int]=None    ,   ) ->   Optional[Any]:
						"""simple docstring"""







						lowerCAmelCase__       =						False
						for name, module in model.named_children():
												if current_key_name is None:
																		lowerCAmelCase__       =						[]
												current_key_name.append(UpperCamelCase_   )
												if isinstance(UpperCamelCase_    ,   nn.Linear   ) and name not in modules_to_not_convert:
																		# Check if the current key is not in the `modules_to_not_convert`
																		lowerCAmelCase__       =						'''.'''.join(UpperCamelCase_   )
																		lowerCAmelCase__       =						True
																		for key in modules_to_not_convert:
																								if (
																								    (key in current_key_name_str) and (key + "." in current_key_name_str)
																								) or key == current_key_name_str:
																														lowerCAmelCase__       =						False
																														break
																		if proceed:
																								# Load bnb module with empty weight and replace ``nn.Linear` module
																								if bnb_quantization_config.load_in_abit:
																														lowerCAmelCase__       =						bnb.nn.LinearabitLt(
																														    module.in_features    ,   module.out_features    ,   module.bias is not None    ,   has_fpaa_weights=UpperCamelCase_    ,   threshold=bnb_quantization_config.llm_inta_threshold    ,   )
																								elif bnb_quantization_config.load_in_abit:
																														lowerCAmelCase__       =						bnb.nn.Linearabit(
																														    module.in_features    ,   module.out_features    ,   module.bias is not None    ,   bnb_quantization_config.bnb_abit_compute_dtype    ,   compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant    ,   quant_type=bnb_quantization_config.bnb_abit_quant_type    ,   )
																								else:
																														raise ValueError("load_in_8bit and load_in_4bit can\'t be both False"   )
																								lowerCAmelCase__       =						module.weight.data
																								if module.bias is not None:
																														lowerCAmelCase__       =						module.bias.data
																								bnb_module.requires_grad_(UpperCamelCase_   )
																								setattr(UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_   )
																								lowerCAmelCase__       =						True
												if len(list(module.children()   )   ) > 0:
																		lowerCAmelCase__       =						_replace_with_bnb_layers(
																		    UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_   )
																		lowerCAmelCase__       =						has_been_replaced | _has_been_replaced
												# Remove the last key for recursion
												current_key_name.pop(-1   )
						return model, has_been_replaced


def        _a  (     UpperCamelCase_					:				Optional[int]   ) ->   Union[str, Any]:
						"""simple docstring"""







						with init_empty_weights():
												lowerCAmelCase__       =						deepcopy(UpperCamelCase_   )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

						lowerCAmelCase__       =						find_tied_parameters(UpperCamelCase_   )
						# For compatibility with Accelerate < 0.18
						if isinstance(UpperCamelCase_    ,   UpperCamelCase_   ):
												lowerCAmelCase__       =						sum(list(tied_params.values()   )    ,   []   ) + list(tied_params.keys()   )
						else:
												lowerCAmelCase__       =						sum(UpperCamelCase_    ,   []   )
						lowerCAmelCase__       =						len(UpperCamelCase_   ) > 0

						# Check if it is a base model
						lowerCAmelCase__       =						False
						if hasattr(UpperCamelCase_    ,   "base_model_prefix"   ):
												lowerCAmelCase__       =						not hasattr(UpperCamelCase_    ,   model.base_model_prefix   )

						# Ignore this for base models (BertModel, GPT2Model, etc.)
						if (not has_tied_params) and is_base_model:
												return []

						# otherwise they have an attached head
						lowerCAmelCase__       =						list(model.named_children()   )
						lowerCAmelCase__       =						[list_modules[-1][0]]

						# add last module together with tied weights
						lowerCAmelCase__       =						set(UpperCamelCase_   ) - set(UpperCamelCase_   )
						lowerCAmelCase__       =						list(set(UpperCamelCase_   )   ) + list(UpperCamelCase_   )

						# remove ".weight" from the keys
						lowerCAmelCase__       =						['''.weight''', '''.bias''']
						lowerCAmelCase__       =						[]
						for name in list_untouched:
												for name_to_remove in names_to_remove:
																		if name_to_remove in name:
																								lowerCAmelCase__       =						name.replace(UpperCamelCase_    ,   ""   )
												filtered_module_names.append(UpperCamelCase_   )

						return filtered_module_names


def        _a  (     UpperCamelCase_					:				Optional[Any]   ) ->   int:
						"""simple docstring"""







						for m in model.modules():
												if isinstance(UpperCamelCase_    ,   bnb.nn.Linearabit   ):
																		return True
						return False


def        _a  (     UpperCamelCase_					:				List[Any]   ) ->   Any:
						"""simple docstring"""







						return next(parameter.parameters()   ).device





def        _a  (     UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				int    ,   UpperCamelCase_					:				str    ,   UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				List[Any]    ,   UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				str   ) ->   Any:
						"""simple docstring"""







						if fpaa_statistics is None:
												set_module_tensor_to_device(UpperCamelCase_    ,   UpperCamelCase_    ,   0    ,   dtype=UpperCamelCase_    ,   value=UpperCamelCase_   )
												lowerCAmelCase__       =						param_name
												lowerCAmelCase__       =						model
												if "." in tensor_name:
																		lowerCAmelCase__       =						tensor_name.split("."   )
																		for split in splits[:-1]:
																								lowerCAmelCase__       =						getattr(UpperCamelCase_    ,   UpperCamelCase_   )
																								if new_module is None:
																														raise ValueError(F"{module} has no attribute {split}."   )
																								lowerCAmelCase__       =						new_module
																		lowerCAmelCase__       =						splits[-1]
												# offload weights
												lowerCAmelCase__       =						False
												offload_weight(module._parameters[tensor_name]    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   index=UpperCamelCase_   )
												if hasattr(module._parameters[tensor_name]    ,   "SCB"   ):
																		offload_weight(
																		    module._parameters[tensor_name].SCB    ,   param_name.replace("weight"    ,   "SCB"   )    ,   UpperCamelCase_    ,   index=UpperCamelCase_    ,   )
						else:
												offload_weight(UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   index=UpperCamelCase_   )
												offload_weight(UpperCamelCase_    ,   param_name.replace("weight"    ,   "SCB"   )    ,   UpperCamelCase_    ,   index=UpperCamelCase_   )

						set_module_tensor_to_device(UpperCamelCase_    ,   UpperCamelCase_    ,   "meta"    ,   dtype=UpperCamelCase_    ,   value=torch.empty(*param.size()   )   )














import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


a_							=    logging.get_logger(__name__)

a_							=    {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

a_							=    {
    '''vocab_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
a_							=    {
    '''vocab_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
a_							=    {
    '''vocab_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}

a_							=    {
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
a_							=    {
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
a_							=    {
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


a_							=    {
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
a_							=    {
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
a_							=    {
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}


class      lowercase__     (			_UpperCAmelCase	):
	a_         =VOCAB_FILES_NAMES
	a_         =CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
	a_         =CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	a_         =CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION





class      lowercase__     (			_UpperCAmelCase	):
	a_         =VOCAB_FILES_NAMES
	a_         =QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
	a_         =QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	a_         =QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION





a_							=    collections.namedtuple(
    '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)

a_							=    collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


a_							=    r'''
    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
    with the format:

    ```
    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
    ```

    Args:
        questions (`str` or `List[str]`):
            The questions to be encoded. You can specify one question for many passages. In this case, the question
            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
            `titles` or `texts`.
        titles (`str` or `List[str]`):
            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
        texts (`str` or `List[str]`):
            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
            Activates and controls padding. Accepts the following values:

            - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
              if provided).
            - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided.
            - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different
              lengths).
        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
            Activates and controls truncation. Accepts the following values:

            - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to
              the maximum acceptable input length for the model if that argument is not provided. This will truncate
              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
              of pairs) is provided.
            - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the first
              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the
              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths
              greater than the model maximum admissible input size).
        max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters.

                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
                is required by one of the truncation/padding parameters. If the model has no specific maximum input
                length (like XLNet) truncation/padding to a maximum length will be deactivated.
        return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `\'tf\'`: Return TensorFlow `tf.constant` objects.
                - `\'pt\'`: Return PyTorch `torch.Tensor` objects.
                - `\'np\'`: Return Numpy `np.ndarray` objects.
        return_attention_mask (`bool`, *optional*):
            Whether or not to return the attention mask. If not set, will return the attention mask according to the
            specific tokenizer\'s default, defined by the `return_outputs` attribute.

            [What are attention masks?](../glossary#attention-mask)

    Returns:
        `Dict[str, List[List[int]]]`: A dictionary with the following keys:

        - `input_ids`: List of token ids to be fed to a model.
        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
    '''


@add_start_docstrings(_UpperCAmelCase	)
class      lowercase__     :

	def __call__(							self		,    __UpperCAmelCase		,    __UpperCAmelCase = None		,    __UpperCAmelCase = None		,    __UpperCAmelCase = False		,    __UpperCAmelCase = False		,    __UpperCAmelCase = None		,    __UpperCAmelCase = None		,    __UpperCAmelCase = None		,    **__UpperCAmelCase		,    )->					BatchEncoding:







							'''simple docstring'''





							if titles is None and texts is None:
													return super().__call__(
													    __UpperCAmelCase		,    padding=__UpperCAmelCase		,    truncation=__UpperCAmelCase		,    max_length=__UpperCAmelCase		,    return_tensors=__UpperCAmelCase		,    return_attention_mask=__UpperCAmelCase		,    **__UpperCAmelCase		,    )
							elif titles is None or texts is None:
													lowerCAmelCase__       =						titles if texts is None else texts
													return super().__call__(
													    __UpperCAmelCase		,    __UpperCAmelCase		,    padding=__UpperCAmelCase		,    truncation=__UpperCAmelCase		,    max_length=__UpperCAmelCase		,    return_tensors=__UpperCAmelCase		,    return_attention_mask=__UpperCAmelCase		,    **__UpperCAmelCase		,    )
							lowerCAmelCase__       =						titles if not isinstance(__UpperCAmelCase		,    __UpperCAmelCase       ) else [titles]
							lowerCAmelCase__       =						texts if not isinstance(__UpperCAmelCase		,    __UpperCAmelCase       ) else [texts]
							lowerCAmelCase__       =						len(__UpperCAmelCase       )
							lowerCAmelCase__       =						questions if not isinstance(__UpperCAmelCase		,    __UpperCAmelCase       ) else [questions] * n_passages
							if len(__UpperCAmelCase       ) != len(__UpperCAmelCase       ):
													raise ValueError(
													    F"There should be as many titles than texts but got {len(__UpperCAmelCase       )} titles and {len(__UpperCAmelCase       )} texts."       )
							lowerCAmelCase__       =						super().__call__(__UpperCAmelCase		,    __UpperCAmelCase		,    padding=__UpperCAmelCase		,    truncation=__UpperCAmelCase       )["input_ids"]
							lowerCAmelCase__       =						super().__call__(__UpperCAmelCase		,    add_special_tokens=__UpperCAmelCase		,    padding=__UpperCAmelCase		,    truncation=__UpperCAmelCase       )["input_ids"]
							lowerCAmelCase__       =						{
							    "input_ids": [
							        (encoded_question_and_title + encoded_text)[:max_length]
							        if max_length is not None and truncation
							        else encoded_question_and_title + encoded_text
							        for encoded_question_and_title, encoded_text in zip(__UpperCAmelCase		,    __UpperCAmelCase       )
							    ]
							}
							if return_attention_mask is not False:
													lowerCAmelCase__       =						[]
													for input_ids in encoded_inputs["input_ids"]:
																			attention_mask.append([int(input_id != self.pad_token_id       ) for input_id in input_ids]       )
													lowerCAmelCase__       =						attention_mask
							return self.pad(__UpperCAmelCase		,    padding=__UpperCAmelCase		,    max_length=__UpperCAmelCase		,    return_tensors=__UpperCAmelCase       )

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase = 16		,    __UpperCAmelCase = 64		,    __UpperCAmelCase = 4		,    )->					List[DPRSpanPrediction]:







							'''simple docstring'''





							lowerCAmelCase__       =						reader_input["input_ids"]
							lowerCAmelCase__      ,							lowerCAmelCase__      ,							lowerCAmelCase__       =						reader_output[:3]
							lowerCAmelCase__       =						len(__UpperCAmelCase       )
							lowerCAmelCase__       =						sorted(range(__UpperCAmelCase       )		,    reverse=__UpperCAmelCase		,    key=relevance_logits.__getitem__       )
							lowerCAmelCase__       =						[]
							for doc_id in sorted_docs:
													lowerCAmelCase__       =						list(input_ids[doc_id]       )
													# assuming question & title information is at the beginning of the sequence
													lowerCAmelCase__       =						sequence_ids.index(self.sep_token_id		,    2       ) + 1  # second sep id
													if sequence_ids[-1] == self.pad_token_id:
																			lowerCAmelCase__       =						sequence_ids.index(self.pad_token_id       )
													else:
																			lowerCAmelCase__       =						len(__UpperCAmelCase       )

													lowerCAmelCase__       =						self._get_best_spans(
													    start_logits=start_logits[doc_id][passage_offset:sequence_len]		,    end_logits=end_logits[doc_id][passage_offset:sequence_len]		,    max_answer_length=__UpperCAmelCase		,    top_spans=__UpperCAmelCase		,    )
													for start_index, end_index in best_spans:
																			start_index += passage_offset
																			end_index += passage_offset
																			nbest_spans_predictions.append(
																			    DPRSpanPrediction(
																			        span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index]		,    relevance_score=relevance_logits[doc_id]		,    doc_id=__UpperCAmelCase		,    start_index=__UpperCAmelCase		,    end_index=__UpperCAmelCase		,    text=self.decode(sequence_ids[start_index : end_index + 1]       )		,    )       )
													if len(__UpperCAmelCase       ) >= num_spans:
																			break
							return nbest_spans_predictions[:num_spans]


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase		,    )->					List[DPRSpanPrediction]:







							'''simple docstring'''





							lowerCAmelCase__       =						[]
							for start_index, start_score in enumerate(__UpperCAmelCase       ):
													for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]       ):
																			scores.append(((start_index, start_index + answer_length), start_score + end_score)       )
							lowerCAmelCase__       =						sorted(__UpperCAmelCase		,    key=lambda __UpperCAmelCase       : x[1]		,    reverse=__UpperCAmelCase       )
							lowerCAmelCase__       =						[]
							for (start_index, end_index), score in scores:
													if start_index > end_index:
																			raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]"       )
													lowerCAmelCase__       =						end_index - start_index + 1
													if length > max_answer_length:
																			raise ValueError(F"Span is too long: {length} > {max_answer_length}"       )
													if any(
													    start_index <= prev_start_index <= prev_end_index <= end_index
													    or prev_start_index <= start_index <= end_index <= prev_end_index
													    for (prev_start_index, prev_end_index) in chosen_span_intervals       ):
																			continue
													chosen_span_intervals.append((start_index, end_index)       )

													if len(__UpperCAmelCase       ) == top_spans:
																			break
							return chosen_span_intervals





@add_end_docstrings(_UpperCAmelCase	)
class      lowercase__     (			_UpperCAmelCase,					_UpperCAmelCase	):
	a_         =VOCAB_FILES_NAMES
	a_         =READER_PRETRAINED_VOCAB_FILES_MAP
	a_         =READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	a_         =READER_PRETRAINED_INIT_CONFIGURATION
	a_         =["""input_ids""", """attention_mask"""]






