





import copy
import inspect

from transformers.testing_utils import require_torch, torch_device
from transformers.utils.backbone_utils import BackboneType



@require_torch
class 				_lowerCAmelCase			:


  '''simple docstring'''
  a_							:				Dict					    =()
  a_							:				List[Any]					    =True







  def UpperCamelCase_       (					self					:    Optional[int]							):


    '''simple docstring'''





    _snake_case      : Any														=		self.config_class

    # test default config
    _snake_case      : List[Any]														=		config_class()
    self.assertIsNotNone(UpperCamelCase							)
    _snake_case      : Optional[int]														=		['stem'] + [f"""stage{idx}""" for idx in range(1					, len(config.depths							) + 1							)]
    self.assertEqual(config.stage_names					, UpperCamelCase							)
    self.assertTrue(set(config.out_features							).issubset(set(config.stage_names							)							)							)

    # Test out_features and out_indices are correctly set
    # out_features and out_indices both None
    _snake_case      : List[str]														=		config_class(out_features=UpperCamelCase					, out_indices=UpperCamelCase							)
    self.assertEqual(config.out_features					, [config.stage_names[-1]]							)
    self.assertEqual(config.out_indices					, [len(config.stage_names							) - 1]							)

    # out_features and out_indices both set
    _snake_case      : List[str]														=		config_class(out_features=['stem', 'stage1']					, out_indices=[0, 1]							)
    self.assertEqual(config.out_features					, ['stem', 'stage1']							)
    self.assertEqual(config.out_indices					, [0, 1]							)

    # Only out_features set
    _snake_case      : Optional[int]														=		config_class(out_features=['stage1', 'stage3']							)
    self.assertEqual(config.out_features					, ['stage1', 'stage3']							)
    self.assertEqual(config.out_indices					, [1, 3]							)

    # Only out_indices set
    _snake_case      : Tuple														=		config_class(out_indices=[0, 2]							)
    self.assertEqual(config.out_features					, [config.stage_names[0], config.stage_names[2]]							)
    self.assertEqual(config.out_indices					, [0, 2]							)

    # Error raised when out_indices do not correspond to out_features
    with self.assertRaises(UpperCamelCase							):
      _snake_case      : Optional[Any]														=		config_class(out_features=['stage1', 'stage2']					, out_indices=[0, 2]							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : List[str]														=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      _snake_case      : str														=		model_class(UpperCamelCase							)
      _snake_case      : Dict														=		inspect.signature(model.forward							)
      # signature.parameters is an OrderedDict => so arg_names order is deterministic
      _snake_case      : Optional[int]														=		[*signature.parameters.keys()]
      _snake_case      : Optional[Any]														=		['pixel_values']
      self.assertListEqual(arg_names[:1]					, UpperCamelCase							)







  def UpperCamelCase_       (					self					:    int							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : Dict														=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      _snake_case      : Dict														=		model_class(UpperCamelCase							)
      self.assertEqual(len(model.channels							)					, len(config.out_features							)							)
      _snake_case      : Tuple														=		model.num_features
      _snake_case      : str														=		[config.stage_names.index(UpperCamelCase							) for feat in config.out_features]
      _snake_case      : List[Any]														=		[num_features[idx] for idx in out_indices]
      self.assertListEqual(model.channels					, UpperCamelCase							)

      _snake_case      : List[str]														=		copy.deepcopy(UpperCamelCase							)
      _snake_case      : Dict														=		None
      _snake_case      : str														=		model_class(UpperCamelCase							)
      self.assertEqual(len(model.channels							)					, 1							)
      self.assertListEqual(model.channels					, [num_features[-1]]							)

      _snake_case      : Optional[Any]														=		copy.deepcopy(UpperCamelCase							)
      _snake_case      : List[Any]														=		None
      _snake_case      : Optional[int]														=		model_class(UpperCamelCase							)
      self.assertEqual(len(model.channels							)					, 1							)
      self.assertListEqual(model.channels					, [num_features[-1]]							)







  def UpperCamelCase_       (					self					:    Any							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : List[str]														=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      _snake_case      : str														=		model_class(UpperCamelCase							)
      model.to(UpperCamelCase							)
      model.eval()
      _snake_case      : List[str]														=		model(**UpperCamelCase							)

      self.assertEqual(len(result.feature_maps							)					, len(config.out_features							)							)
      self.assertEqual(len(model.channels							)					, len(config.out_features							)							)
      self.assertEqual(len(result.feature_maps							)					, len(config.out_indices							)							)
      self.assertEqual(len(model.channels							)					, len(config.out_indices							)							)

      # Check output of last stage is taken if out_features=None, out_indices=None
      _snake_case      : List[str]														=		copy.deepcopy(UpperCamelCase							)
      _snake_case      : Tuple														=		None
      _snake_case      : Union[str, Any]														=		model_class(UpperCamelCase							)
      model.to(UpperCamelCase							)
      model.eval()
      _snake_case      : Optional[Any]														=		model(**UpperCamelCase							)

      self.assertEqual(len(result.feature_maps							)					, 1							)
      self.assertEqual(len(model.channels							)					, 1							)

      _snake_case      : Optional[int]														=		copy.deepcopy(UpperCamelCase							)
      _snake_case      : Tuple														=		None
      _snake_case      : List[Any]														=		model_class(UpperCamelCase							)
      model.to(UpperCamelCase							)
      model.eval()
      _snake_case      : List[Any]														=		model(**UpperCamelCase							)

      self.assertEqual(len(result.feature_maps							)					, 1							)
      self.assertEqual(len(model.channels							)					, 1							)

      # Check backbone can be initialized with fresh weights
      _snake_case      : Dict														=		copy.deepcopy(UpperCamelCase							)
      _snake_case      : List[str]														=		False
      _snake_case      : Any														=		model_class(UpperCamelCase							)
      model.to(UpperCamelCase							)
      model.eval()
      _snake_case      : Tuple														=		model(**UpperCamelCase							)







  def UpperCamelCase_       (					self					:    int							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : Union[str, Any]														=		self.model_tester.prepare_config_and_inputs_for_common()

    for backbone_class in self.all_model_classes:
      _snake_case      : Optional[int]														=		backbone_class(UpperCamelCase							)

      self.assertTrue(hasattr(UpperCamelCase					, 'backbone_type'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'stage_names'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'num_features'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'out_indices'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'out_features'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'out_feature_channels'							)							)
      self.assertTrue(hasattr(UpperCamelCase					, 'channels'							)							)

      self.assertIsInstance(backbone.backbone_type					, UpperCamelCase							)
      # Verify num_features has been initialized in the backbone init
      self.assertIsNotNone(backbone.num_features							)
      self.assertTrue(len(backbone.channels							) == len(backbone.out_indices							)							)
      self.assertTrue(len(backbone.stage_names							) == len(backbone.num_features							)							)
      self.assertTrue(len(backbone.channels							) <= len(backbone.num_features							)							)
      self.assertTrue(len(backbone.out_feature_channels							) == len(backbone.stage_names							)							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : Union[str, Any]														=		self.model_tester.prepare_config_and_inputs_for_common()
    _snake_case      : List[Any]														=		inputs_dict['pixel_values'].shape[0]

    for backbone_class in self.all_model_classes:
      _snake_case      : List[str]														=		backbone_class(UpperCamelCase							)
      backbone.to(UpperCamelCase							)
      backbone.eval()

      _snake_case      : Union[str, Any]														=		backbone(**UpperCamelCase							)

      # Test default outputs and verify feature maps
      self.assertIsInstance(outputs.feature_maps					, UpperCamelCase							)
      self.assertTrue(len(outputs.feature_maps							) == len(backbone.channels							)							)
      for feature_map, n_channels in zip(outputs.feature_maps					, backbone.channels							):
        self.assertTrue(feature_map.shape[:2]					, (batch_size, n_channels)							)
      self.assertIsNone(outputs.hidden_states							)
      self.assertIsNone(outputs.attentions							)

      # Test output_hidden_states=True
      _snake_case      : str														=		backbone(**UpperCamelCase					, output_hidden_states=UpperCamelCase							)
      self.assertIsNotNone(outputs.hidden_states							)
      self.assertTrue(len(outputs.hidden_states							)					, len(backbone.stage_names							)							)
      for hidden_state, n_channels in zip(outputs.hidden_states					, backbone.channels							):
        self.assertTrue(hidden_state.shape[:2]					, (batch_size, n_channels)							)

      # Test output_attentions=True
      if self.has_attentions:
        _snake_case      : Tuple														=		backbone(**UpperCamelCase					, output_attentions=UpperCamelCase							)
        self.assertIsNotNone(outputs.attentions							)











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							)




