


'''simple docstring'''

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,
)


_A      :				List[str] 				=    '''\
@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}
}
'''

_A      :				Any 				=    '''
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.
'''

_A      :				Optional[int] 				=    '''
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     _lowercase					(    datasets.Metric      ):


 '''simple docstring'''






 def a (				self       :     Optional[Any]							)  ->   Tuple:
  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 a (				self       :     Union[str, Any]				,	SCREAMING_SNAKE_CASE__       :     Union[str, Any]				,	SCREAMING_SNAKE_CASE__       :     List[str]				,	SCREAMING_SNAKE_CASE__       :     Optional[int]=1.0							)  ->   Dict:
  __lowerCAmelCase    							=						{p["""id"""]: p["""no_answer_probability"""] for p in predictions}
  __lowerCAmelCase    							=						[{"""paragraphs""": [{"""qas""": references}]}]
  __lowerCAmelCase    							=						{p["""id"""]: p["""prediction_text"""] for p in predictions}

  __lowerCAmelCase    							=						make_qid_to_has_ans(SCREAMING_SNAKE_CASE__							)  # maps qid to True/False
  __lowerCAmelCase    							=						[k for k, v in qid_to_has_ans.items() if v]
  __lowerCAmelCase    							=						[k for k, v in qid_to_has_ans.items() if not v]

  __lowerCAmelCase							,	__lowerCAmelCase    							=						get_raw_scores(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						apply_no_ans_threshold(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						apply_no_ans_threshold(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						make_eval_dict(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)

  if has_ans_qids:
   __lowerCAmelCase    							=						make_eval_dict(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	qid_list=SCREAMING_SNAKE_CASE__							)
   merge_eval(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	"""HasAns"""							)
  if no_ans_qids:
   __lowerCAmelCase    							=						make_eval_dict(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	qid_list=SCREAMING_SNAKE_CASE__							)
   merge_eval(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	"""NoAns"""							)
  find_all_best_thresh(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
  return dict(SCREAMING_SNAKE_CASE__							)







'''simple docstring'''

import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







@skip_mps
class     _lowercase					(    UpperCAmelCase__  ,							UpperCAmelCase__  ,							UpperCAmelCase__  ,							unittest.TestCase      ):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE					:	int				     = StableDiffusionModelEditingPipeline
 _SCREAMING_SNAKE_CASE					:	List[Any]				     = TEXT_TO_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE					:	Tuple				     = TEXT_TO_IMAGE_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE					:	List[Any]				     = TEXT_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE					:	Optional[int]				     = TEXT_TO_IMAGE_IMAGE_PARAMS
 def a (				self       :     Tuple							)  ->   Any:
  torch.manual_seed(0							)
  __lowerCAmelCase    							=						UNetaDConditionModel(
      block_out_channels=(32, 64)				,	layers_per_block=2				,	sample_size=32				,	in_channels=4				,	out_channels=4				,	down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,	up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,	cross_attention_dim=32				,	)
  __lowerCAmelCase    							=						DDIMScheduler()
  torch.manual_seed(0							)
  __lowerCAmelCase    							=						AutoencoderKL(
      block_out_channels=[32, 64]				,	in_channels=3				,	out_channels=3				,	down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,	up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,	latent_channels=4				,	)
  torch.manual_seed(0							)
  __lowerCAmelCase    							=						CLIPTextConfig(
      bos_token_id=0				,	eos_token_id=2				,	hidden_size=32				,	intermediate_size=37				,	layer_norm_eps=1e-0_5				,	num_attention_heads=4				,	num_hidden_layers=5				,	pad_token_id=1				,	vocab_size=10_00				,	)
  __lowerCAmelCase    							=						CLIPTextModel(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

  __lowerCAmelCase    							=						{
      """unet""": unet,
      """scheduler""": scheduler,
      """vae""": vae,
      """text_encoder""": text_encoder,
      """tokenizer""": tokenizer,
      """safety_checker""": None,
      """feature_extractor""": None,
  }
  return components
 def a (				self       :     List[Any]				,	SCREAMING_SNAKE_CASE__       :     Union[str, Any]				,	SCREAMING_SNAKE_CASE__       :     Dict=0							)  ->   Tuple:
  __lowerCAmelCase    							=						torch.manual_seed(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						{
      """prompt""": """A field of roses""",
      """generator""": generator,
      # Setting height and width to None to prevent OOMs on CPU.
      """height""": None,
      """width""": None,
      """num_inference_steps""": 2,
      """guidance_scale""": 6.0,
      """output_type""": """numpy""",
  }
  return inputs
 def a (				self       :     int							)  ->   Optional[int]:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe(**SCREAMING_SNAKE_CASE__							).images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1]
  assert image.shape == (1, 64, 64, 3)

  __lowerCAmelCase    							=						np.array([0.4_7_5_5, 0.5_1_3_2, 0.4_9_7_6, 0.3_9_0_4, 0.3_5_5_4, 0.4_7_6_5, 0.5_1_3_9, 0.5_1_5_8, 0.4_8_8_9]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Dict							)  ->   Tuple:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						"""french fries"""
  __lowerCAmelCase    							=						sd_pipe(**SCREAMING_SNAKE_CASE__				,	negative_prompt=SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						output.images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1]

  assert image.shape == (1, 64, 64, 3)

  __lowerCAmelCase    							=						np.array([0.4_9_9_2, 0.5_1_0_1, 0.5_0_0_4, 0.3_9_4_9, 0.3_6_0_4, 0.4_7_3_5, 0.5_2_1_6, 0.5_2_0_4, 0.4_9_1_3]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Union[str, Any]							)  ->   int:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						EulerAncestralDiscreteScheduler(
      beta_start=0.0_0_0_8_5				,	beta_end=0.0_1_2				,	beta_schedule="""scaled_linear"""							)
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe(**SCREAMING_SNAKE_CASE__							).images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1]

  assert image.shape == (1, 64, 64, 3)

  __lowerCAmelCase    							=						np.array([0.4_7_4_7, 0.5_3_7_2, 0.4_7_7_9, 0.4_9_8_2, 0.5_5_4_3, 0.4_8_1_6, 0.5_2_3_8, 0.4_9_0_4, 0.5_0_2_7]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Optional[int]							)  ->   Optional[int]:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						PNDMScheduler()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
  # the pipeline does not expect pndm so test if it raises error.
  with self.assertRaises(SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase    							=						sd_pipe(**SCREAMING_SNAKE_CASE__							).images
 def a (				self       :     Tuple							)  ->   List[str]:
  super().test_inference_batch_single_identical(expected_max_diff=5e-3							)





 def a (				self       :     Optional[Any]							)  ->   List[str]:
  super().test_attention_slicing_forward_pass(expected_max_diff=5e-3							)







@slow
@require_torch_gpu
class     _lowercase					(    unittest.TestCase      ):


 '''simple docstring'''






 def a (				self       :     Optional[int]							)  ->   List[Any]:
  super().tearDown()
  gc.collect()
  torch.cuda.empty_cache()
 def a (				self       :     Dict				,	SCREAMING_SNAKE_CASE__       :     Dict=0							)  ->   int:
  __lowerCAmelCase    							=						torch.manual_seed(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						{
      """prompt""": """A field of roses""",
      """generator""": generator,
      """num_inference_steps""": 3,
      """guidance_scale""": 7.5,
      """output_type""": """numpy""",
  }
  return inputs
 def a (				self       :     str							)  ->   Tuple:
  __lowerCAmelCase    							=						"""CompVis/stable-diffusion-v1-4"""
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline.from_pretrained(SCREAMING_SNAKE_CASE__				,	safety_checker=SCREAMING_SNAKE_CASE__							)
  pipe.to(SCREAMING_SNAKE_CASE__							)
  pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)
  pipe.enable_attention_slicing()

  __lowerCAmelCase    							=						self.get_inputs()
  __lowerCAmelCase    							=						pipe(**SCREAMING_SNAKE_CASE__							).images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1].flatten()

  assert image.shape == (1, 5_12, 5_12, 3)

  __lowerCAmelCase    							=						np.array(
      [0.6_7_4_9_4_9_6, 0.6_3_8_6_4_5_3, 0.5_1_4_4_3_2_6_7, 0.6_6_0_9_4_9_0_5, 0.6_1_9_2_1_2_1_5, 0.5_4_9_1_3_3_2, 0.5_7_4_4_4_1_7, 0.5_8_0_7_5_1_0_6, 0.5_1_7_4_6_5_8]							)

  assert np.abs(expected_slice - image_slice							).max() < 1e-2

  # make sure image changes after editing
  pipe.edit_model("""A pack of roses"""				,	"""A pack of blue roses"""							)

  __lowerCAmelCase    							=						pipe(**SCREAMING_SNAKE_CASE__							).images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1].flatten()

  assert image.shape == (1, 5_12, 5_12, 3)

  assert np.abs(expected_slice - image_slice							).max() > 1e-1





 def a (				self       :     Tuple							)  ->   Optional[Any]:
  torch.cuda.empty_cache()
  torch.cuda.reset_max_memory_allocated()
  torch.cuda.reset_peak_memory_stats()

  __lowerCAmelCase    							=						"""CompVis/stable-diffusion-v1-4"""
  __lowerCAmelCase    							=						DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__				,	subfolder="""scheduler"""							)
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline.from_pretrained(
      SCREAMING_SNAKE_CASE__				,	scheduler=SCREAMING_SNAKE_CASE__				,	safety_checker=SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						pipe.to(SCREAMING_SNAKE_CASE__							)
  pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)
  pipe.enable_attention_slicing(1							)
  pipe.enable_sequential_cpu_offload()

  __lowerCAmelCase    							=						self.get_inputs()
  __lowerCAmelCase    							=						pipe(**SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						torch.cuda.max_memory_allocated()
  # make sure that less than 4.4 GB is allocated
  assert mem_bytes < 4.4 * 10**9






