





import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
class 							snake_case_		(      lowerCamelCase_    ,       lowerCamelCase_    ,       unittest.TestCase):
		lowerCamelCase     :Optional[int]							=  UNetaDModel
		lowerCamelCase     :int							=  '''sample'''







		@property
		def       __lowercase (		self )					-> Optional[int]:
				lowerCamelCase :			Any    		=4
				lowerCamelCase :			Any    		=1_4
				lowerCamelCase :			Dict    		=1_6

				lowerCamelCase :			Union[str, Any]    		=floats_tensor((batch_size, num_features, seq_len) ).to(snake_case_ )
				lowerCamelCase :			Union[str, Any]    		=torch.tensor([1_0] * batch_size ).to(snake_case_ )

				return {"sample": noise, "timestep": time_step}







		@property
		def       __lowercase (		self )					-> List[Any]:
				return (4, 1_4, 1_6)







		@property
		def       __lowercase (		self )					-> Any:
				return (4, 1_4, 1_6)







		def       __lowercase (		self )					-> int:
				pass







		def       __lowercase (		self )					-> int:
				pass







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Optional[Any]:
				super().test_determinism()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Union[str, Any]:
				super().test_outputs_equivalence()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Union[str, Any]:
				super().test_from_save_pretrained()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Any:
				super().test_from_save_pretrained_variant()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Optional[Any]:
				super().test_model_from_pretrained()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> int:
				super().test_output()







		def       __lowercase (		self )					-> List[str]:
				lowerCamelCase :			Optional[int]    		={
				    'block_out_channels': (3_2, 6_4, 1_2_8, 2_5_6),
				    'in_channels': 1_4,
				    'out_channels': 1_4,
				    'time_embedding_type': 'positional',
				    'use_timestep_embedding': True,
				    'flip_sin_to_cos': False,
				    'freq_shift': 1.0,
				    'out_block_type': 'OutConv1DBlock',
				    'mid_block_type': 'MidResTemporalBlock1D',
				    'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'),
				    'up_block_types': ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D'),
				    'act_fn': 'mish',
				}
				lowerCamelCase :			List[str]    		=self.dummy_input
				return init_dict, inputs_dict







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Optional[int]:
				lowerCamelCase :			Any    		=UNetaDModel.from_pretrained(
				    '''bglick13/hopper-medium-v2-value-function-hor32'''      ,  output_loading_info=snake_case_      ,  subfolder='''unet''' )
				self.assertIsNotNone(snake_case_ )
				self.assertEqual(len(loading_info['''missing_keys'''] )      ,  0 )

				model.to(snake_case_ )
				lowerCamelCase :			Union[str, Any]    		=model(**self.dummy_input )

				assert image is not None, "Make sure output is not None"







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Union[str, Any]:
				lowerCamelCase :			str    		=UNetaDModel.from_pretrained('''bglick13/hopper-medium-v2-value-function-hor32'''      ,  subfolder='''unet''' )
				torch.manual_seed(0 )
				if torch.cuda.is_available():
						torch.cuda.manual_seed_all(0 )

				lowerCamelCase :			Optional[Any]    		=model.config.in_channels
				lowerCamelCase :			List[Any]    		=1_6
				lowerCamelCase :			int    		=torch.randn((1, seq_len, num_features) ).permute(
				    0      ,  2      ,  1 )  # match original, we can update values and remove
				lowerCamelCase :			List[str]    		=torch.full((num_features,)      ,  0 )

				with torch.no_grad():
						lowerCamelCase :			Union[str, Any]    		=model(snake_case_      ,  snake_case_ ).sample.permute(0      ,  2      ,  1 )

				lowerCamelCase :			Tuple    		=output[0, -3:, -3:].flatten()
				# fmt: off
				lowerCamelCase :			Any    		=torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8] )
				# fmt: on
				self.assertTrue(torch.allclose(snake_case_      ,  snake_case_      ,  rtol=1e-3 ) )







		def       __lowercase (		self )					-> Union[str, Any]:
				pass







		@slow
		def       __lowercase (		self )					-> Any:
				lowerCamelCase :			str    		='harmonai/maestro-150k'
				lowerCamelCase :			Optional[Any]    		=UNetaDModel.from_pretrained(snake_case_      ,  subfolder='''unet''' )
				model.to(snake_case_ )

				lowerCamelCase :			Optional[int]    		=6_5_5_3_6
				lowerCamelCase :			Optional[Any]    		=torch.sin(torch.arange(snake_case_ )[None, None, :].repeat(1      ,  2      ,  1 ) ).to(snake_case_ )
				lowerCamelCase :			Dict    		=torch.tensor([1] ).to(snake_case_ )

				with torch.no_grad():
						lowerCamelCase :			str    		=model(snake_case_      ,  snake_case_ ).sample

				lowerCamelCase :			Any    		=output.abs().sum()
				lowerCamelCase :			Tuple    		=output.abs().max()

				assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
				assert (output_max - 0.0_6_0_7).abs() < 4e-4

class 							snake_case_		(      lowerCamelCase_    ,       lowerCamelCase_    ,       unittest.TestCase):
		lowerCamelCase     :Tuple							=  UNetaDModel
		lowerCamelCase     :Any							=  '''sample'''







		@property
		def       __lowercase (		self )					-> str:
				lowerCamelCase :			Dict    		=4
				lowerCamelCase :			int    		=1_4
				lowerCamelCase :			Optional[Any]    		=1_6

				lowerCamelCase :			Dict    		=floats_tensor((batch_size, num_features, seq_len) ).to(snake_case_ )
				lowerCamelCase :			Any    		=torch.tensor([1_0] * batch_size ).to(snake_case_ )

				return {"sample": noise, "timestep": time_step}







		@property
		def       __lowercase (		self )					-> Tuple:
				return (4, 1_4, 1_6)







		@property
		def       __lowercase (		self )					-> Tuple:
				return (4, 1_4, 1)







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Tuple:
				super().test_determinism()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Optional[Any]:
				super().test_outputs_equivalence()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Union[str, Any]:
				super().test_from_save_pretrained()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> List[str]:
				super().test_from_save_pretrained_variant()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> List[Any]:
				super().test_model_from_pretrained()







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Tuple:
				lowerCamelCase :			Dict    		=self.prepare_init_args_and_inputs_for_common()
				lowerCamelCase :			Optional[Any]    		=self.model_class(**snake_case_ )
				model.to(snake_case_ )
				model.eval()

				with torch.no_grad():
						lowerCamelCase :			Optional[Any]    		=model(**snake_case_ )

						if isinstance(snake_case_      ,  snake_case_ ):
								lowerCamelCase :			Any    		=output.sample

				self.assertIsNotNone(snake_case_ )
				lowerCamelCase :			Optional[Any]    		=torch.Size((inputs_dict['''sample'''].shape[0], 1) )
				self.assertEqual(output.shape      ,  snake_case_      ,  '''Input and output shapes do not match''' )







		def       __lowercase (		self )					-> Any:
				pass







		def       __lowercase (		self )					-> List[str]:
				pass







		def       __lowercase (		self )					-> List[str]:
				lowerCamelCase :			Dict    		={
				    'in_channels': 1_4,
				    'out_channels': 1_4,
				    'down_block_types': ['DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'],
				    'up_block_types': [],
				    'out_block_type': 'ValueFunction',
				    'mid_block_type': 'ValueFunctionMidBlock1D',
				    'block_out_channels': [3_2, 6_4, 1_2_8, 2_5_6],
				    'layers_per_block': 1,
				    'downsample_each_block': True,
				    'use_timestep_embedding': True,
				    'freq_shift': 1.0,
				    'flip_sin_to_cos': False,
				    'time_embedding_type': 'positional',
				    'act_fn': 'mish',
				}
				lowerCamelCase :			Optional[Any]    		=self.dummy_input
				return init_dict, inputs_dict







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> Dict:
				lowerCamelCase :			int    		=UNetaDModel.from_pretrained(
				    '''bglick13/hopper-medium-v2-value-function-hor32'''      ,  output_loading_info=snake_case_      ,  subfolder='''value_function''' )
				self.assertIsNotNone(snake_case_ )
				self.assertEqual(len(vf_loading_info['''missing_keys'''] )      ,  0 )

				value_function.to(snake_case_ )
				lowerCamelCase :			List[str]    		=value_function(**self.dummy_input )

				assert image is not None, "Make sure output is not None"







		@unittest.skipIf(torch_device == '''mps'''      ,  '''mish op not supported in MPS''' )
		def       __lowercase (		self )					-> int:
				lowerCamelCase :			Union[str, Any]    		=UNetaDModel.from_pretrained(
				    '''bglick13/hopper-medium-v2-value-function-hor32'''      ,  output_loading_info=snake_case_      ,  subfolder='''value_function''' )
				torch.manual_seed(0 )
				if torch.cuda.is_available():
						torch.cuda.manual_seed_all(0 )

				lowerCamelCase :			List[Any]    		=value_function.config.in_channels
				lowerCamelCase :			Tuple    		=1_4
				lowerCamelCase :			Any    		=torch.randn((1, seq_len, num_features) ).permute(
				    0      ,  2      ,  1 )  # match original, we can update values and remove
				lowerCamelCase :			Union[str, Any]    		=torch.full((num_features,)      ,  0 )

				with torch.no_grad():
						lowerCamelCase :			Tuple    		=value_function(snake_case_      ,  snake_case_ ).sample

				# fmt: off
				lowerCamelCase :			Tuple    		=torch.tensor([1_6_5.2_5] * seq_len )
				# fmt: on
				self.assertTrue(torch.allclose(snake_case_      ,  snake_case_      ,  rtol=1e-3 ) )







		def       __lowercase (		self )					-> Optional[Any]:
				pass


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


snake_case__	:     int      =    '''\
@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}
}
'''

snake_case__	:     List[str]      =    '''
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.
'''

snake_case__	:     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 	__SCREAMING_SNAKE_CASE		(			datasets.Metric			):







  '''simple docstring'''






  def _UpperCamelCase	(					self		):




       '''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 ,						snake_case_ ,						snake_case_ ,						snake_case_=1.0		):




       '''simple docstring'''

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

       UpperCAmelCase_				:  Optional[int]  = make_qid_to_has_ans(snake_case_		)  # maps qid to True/False
       UpperCAmelCase_				:  List[Any]  = [k for k, v in qid_to_has_ans.items() if v]
       UpperCAmelCase_				:  Union[str, Any]  = [k for k, v in qid_to_has_ans.items() if not v]

       UpperCAmelCase_  ,     UpperCAmelCase_				:  Optional[int]  = get_raw_scores(snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  Tuple  = apply_no_ans_threshold(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  Dict  = apply_no_ans_threshold(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  str  = make_eval_dict(snake_case_ ,						snake_case_		)

       if has_ans_qids:
            UpperCAmelCase_				:  Dict  = make_eval_dict(snake_case_ ,						snake_case_ ,						qid_list=snake_case_		)
            merge_eval(snake_case_ ,						snake_case_ ,						'HasAns'		)
       if no_ans_qids:
            UpperCAmelCase_				:  List[str]  = make_eval_dict(snake_case_ ,						snake_case_ ,						qid_list=snake_case_		)
            merge_eval(snake_case_ ,						snake_case_ ,						'NoAns'		)
       find_all_best_thresh(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       return dict(snake_case_		)






