





from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import SchedulerMixin


lowerCAmelCase_        =			logging.get_logger(__name__)  # pylint: disable=invalid-name



@dataclass
class 				_lowerCAmelCase			(	UpperCAmelCase_							):


  '''simple docstring'''
  a_							:				torch.FloatTensor




class 				_lowerCAmelCase			(	UpperCAmelCase_							,			UpperCAmelCase_							):


  '''simple docstring'''
  a_							:				Optional[Any]					    =1







  @register_to_config
  def __init__(					self					:    List[Any]					, UpperCamelCase					:    int = 40					, UpperCamelCase					:    float = 0.0_02					, UpperCamelCase					:    float = 80.0					, UpperCamelCase					:    float = 0.5					, UpperCamelCase					:    float = 1.0					, UpperCamelCase					:    float = 7.0					, UpperCamelCase					:    bool = True					, ):


    '''simple docstring'''





    _snake_case      : List[str]														=		sigma_max

    _snake_case      : Optional[int]														=		np.linspace(0					, 1					, UpperCamelCase							)
    _snake_case      : Union[str, Any]														=		self._convert_to_karras(UpperCamelCase							)
    _snake_case      : Dict														=		self.sigma_to_t(UpperCamelCase							)

    # setable values
    _snake_case      : List[Any]														=		None
    _snake_case      : List[str]														=		torch.from_numpy(UpperCamelCase							)
    _snake_case      : int														=		torch.from_numpy(UpperCamelCase							)
    _snake_case      : List[str]														=		False
    _snake_case      : List[str]														=		False







  def UpperCamelCase_       (					self					:    List[str]					, UpperCamelCase					:    Union[str, Any]					, UpperCamelCase					:    Tuple=None							):


    '''simple docstring'''





    if schedule_timesteps is None:
      _snake_case      : List[str]														=		self.timesteps

    _snake_case      : int														=		(schedule_timesteps == timestep).nonzero()
    return indices.item()







  def UpperCamelCase_       (					self					:    Dict					, UpperCamelCase					:    torch.FloatTensor					, UpperCamelCase					:    Union[float, torch.FloatTensor]							):


    '''simple docstring'''





    if isinstance(UpperCamelCase					, torch.Tensor							):
      _snake_case      : Tuple														=		timestep.to(self.timesteps.device							)
    _snake_case      : List[str]														=		self.index_for_timestep(UpperCamelCase							)
    _snake_case      : Tuple														=		self.sigmas[step_idx]

    _snake_case      : Optional[int]														=		sample / ((sigma**2 + self.config.sigma_data**2) ** 0.5)

    _snake_case      : List[Any]														=		True
    return sample







  def UpperCamelCase_       (					self					:    List[str]					, UpperCamelCase					:    Union[float, np.ndarray]							):


    '''simple docstring'''





    if not isinstance(UpperCamelCase					, np.ndarray							):
      _snake_case      : Optional[Any]														=		np.array(UpperCamelCase					, dtype=np.floataa							)

    _snake_case      : Any														=		10_00 * 0.25 * np.log(sigmas + 1e-4_4							)

    return timesteps







  def UpperCamelCase_       (					self					:    Optional[Any]					, UpperCamelCase					:    Optional[int] = None					, UpperCamelCase					:    Union[str, torch.device] = None					, UpperCamelCase					:    Optional[List[int]] = None					, ):


    '''simple docstring'''





    if num_inference_steps is None and timesteps is None:
      raise ValueError('Exactly one of `num_inference_steps` or `timesteps` must be supplied.'							)

    if num_inference_steps is not None and timesteps is not None:
      raise ValueError('Can only pass one of `num_inference_steps` or `timesteps`.'							)

    # Follow DDPMScheduler custom timesteps logic
    if timesteps is not None:
      for i in range(1					, len(UpperCamelCase							)							):
        if timesteps[i] >= timesteps[i - 1]:
          raise ValueError('`timesteps` must be in descending order.'							)

      if timesteps[0] >= self.config.num_train_timesteps:
        raise ValueError(
            f"""`timesteps` must start before `self.config.train_timesteps`:"""
            f""" {self.config.num_train_timesteps}."""							)

      _snake_case      : Dict														=		np.array(UpperCamelCase					, dtype=np.intaa							)
      _snake_case      : List[str]														=		True
    else:
      if num_inference_steps > self.config.num_train_timesteps:
        raise ValueError(
            f"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"""
            f""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"""
            f""" maximal {self.config.num_train_timesteps} timesteps."""							)

      _snake_case      : List[Any]														=		num_inference_steps

      _snake_case      : List[Any]														=		self.config.num_train_timesteps // self.num_inference_steps
      _snake_case      : Any														=		(np.arange(0					, UpperCamelCase							) * step_ratio).round()[::-1].copy().astype(np.intaa							)
      _snake_case      : List[str]														=		False

    # Map timesteps to Karras sigmas directly for multistep sampling
    # See https://github.com/openai/consistency_models/blob/main/cm/karras_diffusion.py#L675
    _snake_case      : List[Any]														=		self.config.num_train_timesteps
    _snake_case      : List[Any]														=		timesteps[::-1].copy()
    _snake_case      : Optional[Any]														=		ramp / (num_train_timesteps - 1)
    _snake_case      : str														=		self._convert_to_karras(UpperCamelCase							)
    _snake_case      : Optional[Any]														=		self.sigma_to_t(UpperCamelCase							)

    _snake_case      : List[str]														=		np.concatenate([sigmas, [self.sigma_min]]							).astype(np.floataa							)
    _snake_case      : Tuple														=		torch.from_numpy(UpperCamelCase							).to(device=UpperCamelCase							)

    if str(UpperCamelCase							).startswith('mps'							):
      # mps does not support float64
      _snake_case      : Tuple														=		torch.from_numpy(UpperCamelCase							).to(UpperCamelCase					, dtype=torch.floataa							)
    else:
      _snake_case      : Optional[Any]														=		torch.from_numpy(UpperCamelCase							).to(device=UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Any					, UpperCamelCase					:    Dict							):


    '''simple docstring'''





    _snake_case      : float														=		self.config.sigma_min
    _snake_case      : float														=		self.config.sigma_max

    _snake_case      : str														=		self.config.rho
    _snake_case      : Optional[Any]														=		sigma_min ** (1 / rho)
    _snake_case      : List[str]														=		sigma_max ** (1 / rho)
    _snake_case      : Union[str, Any]														=		(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
    return sigmas







  def UpperCamelCase_       (					self					:    Tuple					, UpperCamelCase					:    List[str]							):


    '''simple docstring'''





    _snake_case      : str														=		self.config.sigma_data

    _snake_case      : Dict														=		sigma_data**2 / (sigma**2 + sigma_data**2)
    _snake_case      : Tuple														=		sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
    return c_skip, c_out







  def UpperCamelCase_       (					self					:    str					, UpperCamelCase					:    Dict							):


    '''simple docstring'''





    _snake_case      : Any														=		self.config.sigma_min
    _snake_case      : str														=		self.config.sigma_data

    _snake_case      : int														=		sigma_data**2 / ((sigma - sigma_min) ** 2 + sigma_data**2)
    _snake_case      : str														=		(sigma - sigma_min) * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
    return c_skip, c_out







  def UpperCamelCase_       (					self					:    Tuple					, UpperCamelCase					:    torch.FloatTensor					, UpperCamelCase					:    Union[float, torch.FloatTensor]					, UpperCamelCase					:    torch.FloatTensor					, UpperCamelCase					:    Optional[torch.Generator] = None					, UpperCamelCase					:    bool = True					, ):


    '''simple docstring'''





    if (
        isinstance(UpperCamelCase					, UpperCamelCase							)
        or isinstance(UpperCamelCase					, torch.IntTensor							)
        or isinstance(UpperCamelCase					, torch.LongTensor							)
    ):
      raise ValueError(
          (
              'Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to'
              f""" `{self.__class__}.step()` is not supported. Make sure to pass"""
              ' one of the `scheduler.timesteps` as a timestep.'
          )					, )

    if not self.is_scale_input_called:
      logger.warning(
          'The `scale_model_input` function should be called before `step` to ensure correct denoising. '
          'See `StableDiffusionPipeline` for a usage example.'							)

    if isinstance(UpperCamelCase					, torch.Tensor							):
      _snake_case      : Union[str, Any]														=		timestep.to(self.timesteps.device							)

    _snake_case      : Any														=		self.config.sigma_min
    _snake_case      : Optional[Any]														=		self.config.sigma_max

    _snake_case      : Optional[int]														=		self.index_for_timestep(UpperCamelCase							)

    # sigma_next corresponds to next_t in original implementation
    _snake_case      : int														=		self.sigmas[step_index]
    if step_index + 1 < self.config.num_train_timesteps:
      _snake_case      : Optional[Any]														=		self.sigmas[step_index + 1]
    else:
      # Set sigma_next to sigma_min
      _snake_case      : Any														=		self.sigmas[-1]

    # Get scalings for boundary conditions
    _snake_case							,    _snake_case      : Any														=		self.get_scalings_for_boundary_condition(UpperCamelCase							)

    # 1. Denoise model output using boundary conditions
    _snake_case      : List[str]														=		c_out * model_output + c_skip * sample
    if self.config.clip_denoised:
      _snake_case      : List[Any]														=		denoised.clamp(-1					, 1							)

    # 2. Sample z ~ N(0, s_noise^2 * I)
    # Noise is not used for onestep sampling.
    if len(self.timesteps							) > 1:
      _snake_case      : Optional[Any]														=		randn_tensor(
          model_output.shape					, dtype=model_output.dtype					, device=model_output.device					, generator=UpperCamelCase							)
    else:
      _snake_case      : int														=		torch.zeros_like(UpperCamelCase							)
    _snake_case      : Dict														=		noise * self.config.s_noise

    _snake_case      : Optional[Any]														=		sigma_next.clamp(min=UpperCamelCase					, max=UpperCamelCase							)

    # 3. Return noisy sample
    # tau = sigma_hat, eps = sigma_min
    _snake_case      : Optional[Any]														=		denoised + z * (sigma_hat**2 - sigma_min**2) ** 0.5

    if not return_dict:
      return (prev_sample,)

    return CMStochasticIterativeSchedulerOutput(prev_sample=UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[str]					, UpperCamelCase					:    torch.FloatTensor					, UpperCamelCase					:    torch.FloatTensor					, UpperCamelCase					:    torch.FloatTensor					, ):


    '''simple docstring'''





    _snake_case      : List[str]														=		self.sigmas.to(device=original_samples.device					, dtype=original_samples.dtype							)
    if original_samples.device.type == "mps" and torch.is_floating_point(UpperCamelCase							):
      # mps does not support float64
      _snake_case      : int														=		self.timesteps.to(original_samples.device					, dtype=torch.floataa							)
      _snake_case      : Tuple														=		timesteps.to(original_samples.device					, dtype=torch.floataa							)
    else:
      _snake_case      : Tuple														=		self.timesteps.to(original_samples.device							)
      _snake_case      : Any														=		timesteps.to(original_samples.device							)

    _snake_case      : List[str]														=		[(schedule_timesteps == t).nonzero().item() for t in timesteps]

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

    _snake_case      : List[Any]														=		original_samples + noise * sigma
    return noisy_samples







  def __len__(					self					:    Tuple							):


    '''simple docstring'''





    return self.config.num_train_timesteps











import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


lowerCAmelCase_        =			"""\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

lowerCAmelCase_        =			"""
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
"""

lowerCAmelCase_        =			"""
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer 'id' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - 'id': id of the question-answer pair (see above),
            - 'answers': a list of Dict {'text': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    'exact': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
    'total': Number of score considered
    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'HasAns_f1': The F-score of predicted tokens versus the gold answer
    'HasAns_total': Number of score considered
    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'NoAns_f1': The F-score of predicted tokens versus the gold answer
    'NoAns_total': Number of score considered
    'best_exact': Best exact match (with varying threshold)
    'best_exact_thresh': No-answer probability threshold associated to the best exact match
    'best_f1': Best F1 (with varying threshold)
    'best_f1_thresh': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}
"""



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,			_KWARGS_DESCRIPTION							)
class 				_lowerCAmelCase			(	datasets.Metric							):


  '''simple docstring'''







  def UpperCamelCase_       (					self					:    str							):


    '''simple docstring'''





    return datasets.MetricInfo(
        description=_DESCRIPTION					, citation=_CITATION					, inputs_description=_KWARGS_DESCRIPTION					, features=datasets.Features(
            {
                'predictions': {
                    'id': datasets.Value('string'							),
                    'prediction_text': datasets.Value('string'							),
                    'no_answer_probability': datasets.Value('float32'							),
                },
                'references': {
                    'id': datasets.Value('string'							),
                    'answers': datasets.features.Sequence(
                        {'text': datasets.Value('string'							), 'answer_start': datasets.Value('int32'							)}							),
                },
            }							)					, codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/']					, reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/']					, )







  def UpperCamelCase_       (					self					:    Optional[Any]					, UpperCamelCase					:    List[str]					, UpperCamelCase					:    Optional[Any]					, UpperCamelCase					:    str=1.0							):


    '''simple docstring'''





    _snake_case      : Dict														=		{p['id']: p['no_answer_probability'] for p in predictions}
    _snake_case      : Dict														=		[{'paragraphs': [{'qas': references}]}]
    _snake_case      : Dict														=		{p['id']: p['prediction_text'] for p in predictions}

    _snake_case      : Optional[Any]														=		make_qid_to_has_ans(UpperCamelCase							)  # maps qid to True/False
    _snake_case      : str														=		[k for k, v in qid_to_has_ans.items() if v]
    _snake_case      : Optional[Any]														=		[k for k, v in qid_to_has_ans.items() if not v]

    _snake_case							,    _snake_case      : Union[str, Any]														=		get_raw_scores(UpperCamelCase					, UpperCamelCase							)
    _snake_case      : int														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : List[Any]														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : Optional[Any]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase							)

    if has_ans_qids:
      _snake_case      : Optional[int]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'HasAns'							)
    if no_ans_qids:
      _snake_case      : List[str]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'NoAns'							)
    find_all_best_thresh(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    return dict(UpperCamelCase							)




