


import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput



def      __lowerCAmelCase    (				snake_case						:     int    ,   snake_case						:     Union[str, Any]=0.999    ,   snake_case						:     Union[str, Any]="cosine"    ,   )							->				List[Any]:
   if alpha_transform_type == "cosine":

      def alpha_bar_fn(snake_case						:     Dict			):
         return math.cos((t + 0.008) / 1.008 * math.pi / 2			) ** 2

   elif alpha_transform_type == "exp":

      def alpha_bar_fn(snake_case						:     Optional[int]			):
         return math.exp(t * -12.0			)

   else:
      raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}'			)

   __lowerCamelCase:					Optional[Any]	 =						[]
   for i in range(snake_case			):
      __lowerCamelCase:					List[str]	 =						i / num_diffusion_timesteps
      __lowerCamelCase:					List[str]	 =						(i + 1) / num_diffusion_timesteps
      betas.append(min(1 - alpha_bar_fn(snake_case			) / alpha_bar_fn(snake_case			)    ,   snake_case			)			)
   return torch.tensor(snake_case    ,   dtype=torch.floataa			)







class 							a       (      _UpperCAmelCase  ,_UpperCAmelCase ):
     UpperCAmelCase__			:	Any       =						[e.name for e in KarrasDiffusionSchedulers]
     UpperCAmelCase__			:	List[str]       =						2





     @register_to_config
     def __init__(     self       :					int     ,						SCREAMING_SNAKE_CASE_       :					int = 1000     ,						SCREAMING_SNAKE_CASE_       :					float = 0.0_0085     ,						SCREAMING_SNAKE_CASE_       :					float = 0.012     ,						SCREAMING_SNAKE_CASE_       :					str = "linear"     ,						SCREAMING_SNAKE_CASE_       :					Optional[Union[np.ndarray, List[float]]] = None     ,						SCREAMING_SNAKE_CASE_       :					str = "epsilon"     ,						SCREAMING_SNAKE_CASE_       :					str = "linspace"     ,						SCREAMING_SNAKE_CASE_       :					int = 0     ,						):
        if trained_betas is not None:
           __lowerCamelCase:					Any	 =						torch.tensor(SCREAMING_SNAKE_CASE_     ,						dtype=torch.floataa				)
        elif beta_schedule == "linear":
           __lowerCamelCase:					Union[str, Any]	 =						torch.linspace(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						dtype=torch.floataa				)
        elif beta_schedule == "scaled_linear":
           # this schedule is very specific to the latent diffusion model.
           __lowerCamelCase:					Union[str, Any]	 =						(
               torch.linspace(beta_start**0.5     ,						beta_end**0.5     ,						SCREAMING_SNAKE_CASE_     ,						dtype=torch.floataa				) ** 2
           )
        elif beta_schedule == "squaredcos_cap_v2":
           # Glide cosine schedule
           __lowerCamelCase:					List[Any]	 =						betas_for_alpha_bar(SCREAMING_SNAKE_CASE_				)
        else:
           raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}'				)

        __lowerCamelCase:					int	 =						1.0 - self.betas
        __lowerCamelCase:					List[Any]	 =						torch.cumprod(self.alphas     ,						dim=0				)

        #  set all values
        self.set_timesteps(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					str     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]=None				):
        if schedule_timesteps is None:
           __lowerCamelCase:					List[str]	 =						self.timesteps

        __lowerCamelCase:					Union[str, Any]	 =						(schedule_timesteps == timestep).nonzero()

        # The sigma index that is taken for the **very** first `step`
        # is always the second index (or the last index if there is only 1)
        # This way we can ensure we don't accidentally skip a sigma in
        # case we start in the middle of the denoising schedule (e.g. for image-to-image)
        if len(self._index_counter				) == 0:
           __lowerCamelCase:					Tuple	 =						1 if len(SCREAMING_SNAKE_CASE_				) > 1 else 0
        else:
           __lowerCamelCase:					Any	 =						timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_				) else timestep
           __lowerCamelCase:					Dict	 =						self._index_counter[timestep_int]

        return indices[pos].item()





     @property
     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        # standard deviation of the initial noise distribution
        if self.config.timestep_spacing in ["linspace", "trailing"]:
           return self.sigmas.max()

        return (self.sigmas.max() ** 2 + 1) ** 0.5





     def 			SCREAMING_SNAKE_CASE__							(     self       :					int     ,						SCREAMING_SNAKE_CASE_       :					torch.FloatTensor     ,						SCREAMING_SNAKE_CASE_       :					Union[float, torch.FloatTensor]     ,						):
        __lowerCamelCase:					Any	 =						self.index_for_timestep(SCREAMING_SNAKE_CASE_				)

        if self.state_in_first_order:
           __lowerCamelCase:					Tuple	 =						self.sigmas[step_index]
        else:
           __lowerCamelCase:					Optional[int]	 =						self.sigmas_interpol[step_index - 1]

        __lowerCamelCase:					Optional[int]	 =						sample / ((sigma**2 + 1) ** 0.5)
        return sample





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]     ,						SCREAMING_SNAKE_CASE_       :					int     ,						SCREAMING_SNAKE_CASE_       :					Union[str, torch.device] = None     ,						SCREAMING_SNAKE_CASE_       :					Optional[int] = None     ,						):
        __lowerCamelCase:					Optional[int]	 =						num_inference_steps

        __lowerCamelCase:					Tuple	 =						num_train_timesteps or self.config.num_train_timesteps

        # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
        if self.config.timestep_spacing == "linspace":
           __lowerCamelCase:					int	 =						np.linspace(0     ,						num_train_timesteps - 1     ,						SCREAMING_SNAKE_CASE_     ,						dtype=SCREAMING_SNAKE_CASE_				)[::-1].copy()
        elif self.config.timestep_spacing == "leading":
           __lowerCamelCase:					int	 =						num_train_timesteps // self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           __lowerCamelCase:					str	 =						(np.arange(0     ,						SCREAMING_SNAKE_CASE_				) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_				)
           timesteps += self.config.steps_offset
        elif self.config.timestep_spacing == "trailing":
           __lowerCamelCase:					int	 =						num_train_timesteps / self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           __lowerCamelCase:					Union[str, Any]	 =						(np.arange(SCREAMING_SNAKE_CASE_     ,						0     ,						-step_ratio				)).round().copy().astype(SCREAMING_SNAKE_CASE_				)
           timesteps -= 1
        else:
           raise ValueError(
               F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'				)

        __lowerCamelCase:					List[str]	 =						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5				)
        __lowerCamelCase:					int	 =						torch.from_numpy(np.log(SCREAMING_SNAKE_CASE_				)				).to(SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Union[str, Any]	 =						np.interp(SCREAMING_SNAKE_CASE_     ,						np.arange(0     ,						len(SCREAMING_SNAKE_CASE_				)				)     ,						SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						np.concatenate([sigmas, [0.0]]				).astype(np.floataa				)
        __lowerCamelCase:					Any	 =						torch.from_numpy(SCREAMING_SNAKE_CASE_				).to(device=SCREAMING_SNAKE_CASE_				)

        # compute up and down sigmas
        __lowerCamelCase:					List[Any]	 =						sigmas.roll(-1				)
        __lowerCamelCase:					int	 =						0.0
        __lowerCamelCase:					Dict	 =						(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
        __lowerCamelCase:					List[Any]	 =						(sigmas_next**2 - sigmas_up**2) ** 0.5
        __lowerCamelCase:					List[Any]	 =						0.0

        # compute interpolated sigmas
        __lowerCamelCase:					Optional[int]	 =						sigmas.log().lerp(sigmas_down.log()     ,						0.5				).exp()
        __lowerCamelCase:					str	 =						0.0

        # set sigmas
        __lowerCamelCase:					Dict	 =						torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2				), sigmas[-1:]]				)
        __lowerCamelCase:					Union[str, Any]	 =						torch.cat(
            [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2				), sigmas_interpol[-1:]]				)
        __lowerCamelCase:					Dict	 =						torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2				), sigmas_up[-1:]]				)
        __lowerCamelCase:					Dict	 =						torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2				), sigmas_down[-1:]]				)

        if str(SCREAMING_SNAKE_CASE_				).startswith("""mps"""				):
           # mps does not support float64
           __lowerCamelCase:					List[Any]	 =						torch.from_numpy(SCREAMING_SNAKE_CASE_				).to(SCREAMING_SNAKE_CASE_     ,						dtype=torch.floataa				)
        else:
           __lowerCamelCase:					Union[str, Any]	 =						torch.from_numpy(SCREAMING_SNAKE_CASE_				).to(SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Dict	 =						self.sigma_to_t(SCREAMING_SNAKE_CASE_				).to(SCREAMING_SNAKE_CASE_     ,						dtype=timesteps.dtype				)
        __lowerCamelCase:					Any	 =						torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])     ,						dim=-1				).flatten()

        __lowerCamelCase:					str	 =						torch.cat([timesteps[:1], interleaved_timesteps]				)

        __lowerCamelCase:					Union[str, Any]	 =						None

        # for exp beta schedules, such as the one for `pipeline_shap_e.py`
        # we need an index counter
        __lowerCamelCase:					Tuple	 =						defaultdict(SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					str     ,						SCREAMING_SNAKE_CASE_       :					List[str]				):
        # get log sigma
        __lowerCamelCase:					str	 =						sigma.log()

        # get distribution
        __lowerCamelCase:					List[Any]	 =						log_sigma - self.log_sigmas[:, None]

        # get sigmas range
        __lowerCamelCase:					Union[str, Any]	 =						dists.ge(0				).cumsum(dim=0				).argmax(dim=0				).clamp(max=self.log_sigmas.shape[0] - 2				)
        __lowerCamelCase:					List[Any]	 =						low_idx + 1

        __lowerCamelCase:					List[Any]	 =						self.log_sigmas[low_idx]
        __lowerCamelCase:					str	 =						self.log_sigmas[high_idx]

        # interpolate sigmas
        __lowerCamelCase:					Tuple	 =						(low - log_sigma) / (low - high)
        __lowerCamelCase:					List[Any]	 =						w.clamp(0     ,						1				)

        # transform interpolation to time range
        __lowerCamelCase:					str	 =						(1 - w) * low_idx + w * high_idx
        __lowerCamelCase:					Union[str, Any]	 =						t.view(sigma.shape				)
        return t





     @property
     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        return self.sample is None





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					Union[torch.FloatTensor, np.ndarray]     ,						SCREAMING_SNAKE_CASE_       :					Union[float, torch.FloatTensor]     ,						SCREAMING_SNAKE_CASE_       :					Union[torch.FloatTensor, np.ndarray]     ,						SCREAMING_SNAKE_CASE_       :					Optional[torch.Generator] = None     ,						SCREAMING_SNAKE_CASE_       :					bool = True     ,						):
        __lowerCamelCase:					Tuple	 =						self.index_for_timestep(SCREAMING_SNAKE_CASE_				)

        # advance index counter by 1
        __lowerCamelCase:					Any	 =						timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_				) else timestep
        self._index_counter[timestep_int] += 1

        if self.state_in_first_order:
           __lowerCamelCase:					List[Any]	 =						self.sigmas[step_index]
           __lowerCamelCase:					int	 =						self.sigmas_interpol[step_index]
           __lowerCamelCase:					Tuple	 =						self.sigmas_up[step_index]
           __lowerCamelCase:					Optional[Any]	 =						self.sigmas_down[step_index - 1]
        else:
           # 2nd order / KPDM2's method
           __lowerCamelCase:					Any	 =						self.sigmas[step_index - 1]
           __lowerCamelCase:					List[str]	 =						self.sigmas_interpol[step_index - 1]
           __lowerCamelCase:					Optional[int]	 =						self.sigmas_up[step_index - 1]
           __lowerCamelCase:					List[Any]	 =						self.sigmas_down[step_index - 1]

        # currently only gamma=0 is supported. This usually works best anyways.
        # We can support gamma in the future but then need to scale the timestep before
        # passing it to the model which requires a change in API
        __lowerCamelCase:					int	 =						0
        __lowerCamelCase:					Any	 =						sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

        __lowerCamelCase:					Any	 =						model_output.device
        __lowerCamelCase:					Optional[Any]	 =						randn_tensor(model_output.shape     ,						dtype=model_output.dtype     ,						device=SCREAMING_SNAKE_CASE_     ,						generator=SCREAMING_SNAKE_CASE_				)

        # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
        if self.config.prediction_type == "epsilon":
           __lowerCamelCase:					Dict	 =						sigma_hat if self.state_in_first_order else sigma_interpol
           __lowerCamelCase:					List[Any]	 =						sample - sigma_input * model_output
        elif self.config.prediction_type == "v_prediction":
           __lowerCamelCase:					List[Any]	 =						sigma_hat if self.state_in_first_order else sigma_interpol
           __lowerCamelCase:					Tuple	 =						model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
               sample / (sigma_input**2 + 1)
           )
        elif self.config.prediction_type == "sample":
           raise NotImplementedError("""prediction_type not implemented yet: sample"""				)
        else:
           raise ValueError(
               F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'				)

        if self.state_in_first_order:
           # 2. Convert to an ODE derivative for 1st order
           __lowerCamelCase:					Dict	 =						(sample - pred_original_sample) / sigma_hat
           # 3. delta timestep
           __lowerCamelCase:					List[Any]	 =						sigma_interpol - sigma_hat

           # store for 2nd order step
           __lowerCamelCase:					Optional[int]	 =						sample
           __lowerCamelCase:					Tuple	 =						dt
           __lowerCamelCase:					Optional[int]	 =						sample + derivative * dt
        else:
           # DPM-Solver-2
           # 2. Convert to an ODE derivative for 2nd order
           __lowerCamelCase:					Optional[int]	 =						(sample - pred_original_sample) / sigma_interpol
           # 3. delta timestep
           __lowerCamelCase:					str	 =						sigma_down - sigma_hat

           __lowerCamelCase:					Tuple	 =						self.sample
           __lowerCamelCase:					Dict	 =						None

           __lowerCamelCase:					List[Any]	 =						sample + derivative * dt
           __lowerCamelCase:					Optional[int]	 =						prev_sample + noise * sigma_up

        if not return_dict:
           return (prev_sample,)

        return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]     ,						SCREAMING_SNAKE_CASE_       :					torch.FloatTensor     ,						SCREAMING_SNAKE_CASE_       :					torch.FloatTensor     ,						SCREAMING_SNAKE_CASE_       :					torch.FloatTensor     ,						):
        # Make sure sigmas and timesteps have the same device and dtype as original_samples
        __lowerCamelCase:					List[str]	 =						self.sigmas.to(device=original_samples.device     ,						dtype=original_samples.dtype				)
        if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_				):
           # mps does not support float64
           __lowerCamelCase:					str	 =						self.timesteps.to(original_samples.device     ,						dtype=torch.floataa				)
           __lowerCamelCase:					Optional[Any]	 =						timesteps.to(original_samples.device     ,						dtype=torch.floataa				)
        else:
           __lowerCamelCase:					Union[str, Any]	 =						self.timesteps.to(original_samples.device				)
           __lowerCamelCase:					List[Any]	 =						timesteps.to(original_samples.device				)

        __lowerCamelCase:					Optional[Any]	 =						[self.index_for_timestep(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_				) for t in timesteps]

        __lowerCamelCase:					List[str]	 =						sigmas[step_indices].flatten()
        while len(sigma.shape				) < len(original_samples.shape				):
           __lowerCamelCase:					int	 =						sigma.unsqueeze(-1				)

        __lowerCamelCase:					Dict	 =						original_samples + noise * sigma
        return noisy_samples







     def __len__(     self       :					Any				):
        return self.config.num_train_timesteps






import tempfile
import unittest

from transformers import DPRConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
   from transformers.models.dpr.modeling_dpr import (
       DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
       DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
       DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
   )



class 							a       :





     def __init__(     self       :					str     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					List[str]=13     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]=7     ,						SCREAMING_SNAKE_CASE_       :					List[str]=False     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=True     ,						SCREAMING_SNAKE_CASE_       :					str=True     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]=True     ,						SCREAMING_SNAKE_CASE_       :					Any=99     ,						SCREAMING_SNAKE_CASE_       :					Dict=32     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]=5     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=4     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]=37     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]="gelu"     ,						SCREAMING_SNAKE_CASE_       :					Any=0.1     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]=0.1     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]=512     ,						SCREAMING_SNAKE_CASE_       :					Any=16     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]=2     ,						SCREAMING_SNAKE_CASE_       :					str=0.02     ,						SCREAMING_SNAKE_CASE_       :					Tuple=3     ,						SCREAMING_SNAKE_CASE_       :					Any=4     ,						SCREAMING_SNAKE_CASE_       :					Tuple=None     ,						SCREAMING_SNAKE_CASE_       :					str=0     ,						):
        __lowerCamelCase:					Optional[Any]	 =						parent
        __lowerCamelCase:					Union[str, Any]	 =						batch_size
        __lowerCamelCase:					str	 =						seq_length
        __lowerCamelCase:					str	 =						is_training
        __lowerCamelCase:					Optional[Any]	 =						use_input_mask
        __lowerCamelCase:					Union[str, Any]	 =						use_token_type_ids
        __lowerCamelCase:					Any	 =						use_labels
        __lowerCamelCase:					str	 =						vocab_size
        __lowerCamelCase:					Tuple	 =						hidden_size
        __lowerCamelCase:					str	 =						num_hidden_layers
        __lowerCamelCase:					Dict	 =						num_attention_heads
        __lowerCamelCase:					int	 =						intermediate_size
        __lowerCamelCase:					Any	 =						hidden_act
        __lowerCamelCase:					Dict	 =						hidden_dropout_prob
        __lowerCamelCase:					str	 =						attention_probs_dropout_prob
        __lowerCamelCase:					Optional[Any]	 =						max_position_embeddings
        __lowerCamelCase:					Optional[Any]	 =						type_vocab_size
        __lowerCamelCase:					Optional[int]	 =						type_sequence_label_size
        __lowerCamelCase:					List[str]	 =						initializer_range
        __lowerCamelCase:					Tuple	 =						num_labels
        __lowerCamelCase:					str	 =						num_choices
        __lowerCamelCase:					Union[str, Any]	 =						scope
        __lowerCamelCase:					Dict	 =						projection_dim





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        __lowerCamelCase:					int	 =						ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size				)

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

        __lowerCamelCase:					int	 =						None
        if self.use_token_type_ids:
           __lowerCamelCase:					Union[str, Any]	 =						ids_tensor([self.batch_size, self.seq_length]     ,						self.type_vocab_size				)

        __lowerCamelCase:					Optional[int]	 =						None
        __lowerCamelCase:					int	 =						None
        __lowerCamelCase:					List[Any]	 =						None
        if self.use_labels:
           __lowerCamelCase:					List[str]	 =						ids_tensor([self.batch_size]     ,						self.type_sequence_label_size				)
           __lowerCamelCase:					str	 =						ids_tensor([self.batch_size, self.seq_length]     ,						self.num_labels				)
           __lowerCamelCase:					Optional[int]	 =						ids_tensor([self.batch_size]     ,						self.num_choices				)

        __lowerCamelCase:					int	 =						self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        return DPRConfig(
            projection_dim=self.projection_dim     ,						vocab_size=self.vocab_size     ,						hidden_size=self.hidden_size     ,						num_hidden_layers=self.num_hidden_layers     ,						num_attention_heads=self.num_attention_heads     ,						intermediate_size=self.intermediate_size     ,						hidden_act=self.hidden_act     ,						hidden_dropout_prob=self.hidden_dropout_prob     ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,						max_position_embeddings=self.max_position_embeddings     ,						type_vocab_size=self.type_vocab_size     ,						initializer_range=self.initializer_range     ,						)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					str     ,						SCREAMING_SNAKE_CASE_       :					int     ,						SCREAMING_SNAKE_CASE_       :					Dict     ,						SCREAMING_SNAKE_CASE_       :					Tuple     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					Dict     ,						SCREAMING_SNAKE_CASE_       :					List[str]				):
        __lowerCamelCase:					Union[str, Any]	 =						DPRContextEncoder(config=SCREAMING_SNAKE_CASE_				)
        model.to(SCREAMING_SNAKE_CASE_				)
        model.eval()
        __lowerCamelCase:					int	 =						model(SCREAMING_SNAKE_CASE_     ,						attention_mask=SCREAMING_SNAKE_CASE_     ,						token_type_ids=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[Any]	 =						model(SCREAMING_SNAKE_CASE_     ,						token_type_ids=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Any	 =						model(SCREAMING_SNAKE_CASE_				)
        self.parent.assertEqual(result.pooler_output.shape     ,						(self.batch_size, self.projection_dim or self.hidden_size)				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]     ,						SCREAMING_SNAKE_CASE_       :					List[Any]     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					int     ,						SCREAMING_SNAKE_CASE_       :					Dict     ,						SCREAMING_SNAKE_CASE_       :					str     ,						SCREAMING_SNAKE_CASE_       :					Tuple				):
        __lowerCamelCase:					List[Any]	 =						DPRQuestionEncoder(config=SCREAMING_SNAKE_CASE_				)
        model.to(SCREAMING_SNAKE_CASE_				)
        model.eval()
        __lowerCamelCase:					int	 =						model(SCREAMING_SNAKE_CASE_     ,						attention_mask=SCREAMING_SNAKE_CASE_     ,						token_type_ids=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						model(SCREAMING_SNAKE_CASE_     ,						token_type_ids=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Union[str, Any]	 =						model(SCREAMING_SNAKE_CASE_				)
        self.parent.assertEqual(result.pooler_output.shape     ,						(self.batch_size, self.projection_dim or self.hidden_size)				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any     ,						SCREAMING_SNAKE_CASE_       :					str     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]     ,						SCREAMING_SNAKE_CASE_       :					Dict     ,						SCREAMING_SNAKE_CASE_       :					List[Any]     ,						SCREAMING_SNAKE_CASE_       :					Optional[Any]				):
        __lowerCamelCase:					Optional[Any]	 =						DPRReader(config=SCREAMING_SNAKE_CASE_				)
        model.to(SCREAMING_SNAKE_CASE_				)
        model.eval()
        __lowerCamelCase:					Any	 =						model(
            SCREAMING_SNAKE_CASE_     ,						attention_mask=SCREAMING_SNAKE_CASE_     ,						)

        self.parent.assertEqual(result.start_logits.shape     ,						(self.batch_size, self.seq_length)				)
        self.parent.assertEqual(result.end_logits.shape     ,						(self.batch_size, self.seq_length)				)
        self.parent.assertEqual(result.relevance_logits.shape     ,						(self.batch_size,)				)







     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        __lowerCamelCase:					Any	 =						self.prepare_config_and_inputs()
        (
            (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  
        ):					Dict	 =						config_and_inputs
        __lowerCamelCase:					List[str]	 =						{"""input_ids""": input_ids}
        return config, inputs_dict



@require_torch
class 							a       (      _UpperCAmelCase  ,_UpperCAmelCase  ,unittest.TestCase ):
     UpperCAmelCase__			:	Dict       =						(
         (
             DPRContextEncoder,
             DPRQuestionEncoder,
             DPRReader,
         )
         if is_torch_available()
         else ()
     )
     UpperCAmelCase__			:	List[str]       =						{"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}

     UpperCAmelCase__			:	str       =						False
     UpperCAmelCase__			:	Optional[Any]       =						False  # why?
     UpperCAmelCase__			:	List[Any]       =						False
     UpperCAmelCase__			:	int       =						False





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]				):
        __lowerCamelCase:					str	 =						DPRModelTester(self				)
        __lowerCamelCase:					Dict	 =						ConfigTester(self     ,						config_class=SCREAMING_SNAKE_CASE_     ,						hidden_size=37				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        self.config_tester.run_common_tests()





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					Optional[Any]	 =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_context_encoder(*SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					int				):
        __lowerCamelCase:					Any	 =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_question_encoder(*SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Dict				):
        __lowerCamelCase:					str	 =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_reader(*SCREAMING_SNAKE_CASE_				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        __lowerCamelCase:					str	 =						self.model_tester.prepare_config_and_inputs()[0]

        __lowerCamelCase:					Optional[int]	 =						DPRQuestionEncoder(config=SCREAMING_SNAKE_CASE_				)
        model.to(SCREAMING_SNAKE_CASE_				)
        model.eval()

        with tempfile.TemporaryDirectory() as tmp_dirname:
           model.save_pretrained(SCREAMING_SNAKE_CASE_				)
           __lowerCamelCase:					List[Any]	 =						DPRQuestionEncoder.from_pretrained(SCREAMING_SNAKE_CASE_     ,						projection_dim=512				)

        self.assertIsNotNone(SCREAMING_SNAKE_CASE_				)







     @slow
     def 			SCREAMING_SNAKE_CASE__							(     self       :					Dict				):
        for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:					Dict	 =						DPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE_				)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_				)

        for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:					Any	 =						DPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE_				)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_				)

        for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:					Tuple	 =						DPRQuestionEncoder.from_pretrained(SCREAMING_SNAKE_CASE_				)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_				)

        for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:					Optional[int]	 =						DPRReader.from_pretrained(SCREAMING_SNAKE_CASE_				)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_				)



@require_torch
class 							a       (      unittest.TestCase ):





     @slow
     def 			SCREAMING_SNAKE_CASE__							(     self       :					Union[str, Any]				):
        __lowerCamelCase:					Union[str, Any]	 =						DPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""     ,						return_dict=SCREAMING_SNAKE_CASE_				)
        model.to(SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Tuple	 =						torch.tensor(
            [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]     ,						dtype=torch.long     ,						device=SCREAMING_SNAKE_CASE_				)  # [CLS] hello, is my dog cute? [SEP]
        __lowerCamelCase:					Tuple	 =						model(SCREAMING_SNAKE_CASE_				)[0]  # embedding shape = (1, 768)
        # compare the actual values for a slice.
        __lowerCamelCase:					Dict	 =						torch.tensor(
            [
                [
                    0.0323_6253,
                    0.1275_3335,
                    0.1681_8509,
                    0.0027_9786,
                    0.389_6933,
                    0.2426_4945,
                    0.217_8971,
                    -0.0233_5227,
                    -0.0848_1959,
                    -0.1432_4117,
                ]
            ]     ,						dtype=torch.float     ,						device=SCREAMING_SNAKE_CASE_     ,						)
        self.assertTrue(torch.allclose(output[:, :10]     ,						SCREAMING_SNAKE_CASE_     ,						atol=1E-4				)				)







     @slow
     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        __lowerCamelCase:					Dict	 =						DPRReaderTokenizer.from_pretrained("""facebook/dpr-reader-single-nq-base"""				)
        __lowerCamelCase:					Optional[Any]	 =						DPRReader.from_pretrained("""facebook/dpr-reader-single-nq-base"""				)
        model.to(SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					int	 =						tokenizer(
            questions="""What is love ?"""     ,						titles="""Haddaway"""     ,						texts="""What Is Love is a song recorded by the artist Haddaway"""     ,						padding=SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""     ,						)
        encoded_inputs.to(SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Optional[Any]	 =						model(**SCREAMING_SNAKE_CASE_				)

        # compare the actual values for a slice.
        __lowerCamelCase:					Optional[Any]	 =						torch.tensor(
            [[-10.3005, -10.7765, -11.4872, -11.6841, -11.9312, -10.3002, -9.8544, -11.7378, -12.0821, -10.2975]]     ,						dtype=torch.float     ,						device=SCREAMING_SNAKE_CASE_     ,						)

        __lowerCamelCase:					Dict	 =						torch.tensor(
            [[-11.0684, -11.7041, -11.5397, -10.3465, -10.8791, -6.8443, -11.9959, -11.0364, -10.0096, -6.8405]]     ,						dtype=torch.float     ,						device=SCREAMING_SNAKE_CASE_     ,						)
        self.assertTrue(torch.allclose(outputs.start_logits[:, :10]     ,						SCREAMING_SNAKE_CASE_     ,						atol=1E-4				)				)
        self.assertTrue(torch.allclose(outputs.end_logits[:, :10]     ,						SCREAMING_SNAKE_CASE_     ,						atol=1E-4				)				)


