

'''simple docstring'''
import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


_lowerCamelCase      					=     re.compile(R"""\b(a|an|the)\b""", re.UNICODE)

_lowerCamelCase      					=     None


def  a__       (    )     ->					Tuple:


	"""simple docstring"""





	UpperCAmelCase_     :      Optional[Any]						=  argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0."				)
	parser.add_argument("data_file"	,				metavar="data.json"	,				help="Input data JSON file."				)
	parser.add_argument("pred_file"	,				metavar="pred.json"	,				help="Model predictions."				)
	parser.add_argument(
	    "--out-file"	,				"-o"	,				metavar="eval.json"	,				help="Write accuracy metrics to file (default is stdout)."				)
	parser.add_argument(
	    "--na-prob-file"	,				"-n"	,				metavar="na_prob.json"	,				help="Model estimates of probability of no answer."				)
	parser.add_argument(
	    "--na-prob-thresh"	,				"-t"	,				type=_SCREAMING_SNAKE_CASE	,				default=1.0	,				help="Predict \"\" if no-answer probability exceeds this (default = 1.0)."	,				)
	parser.add_argument(
	    "--out-image-dir"	,				"-p"	,				metavar="out_images"	,				default=_SCREAMING_SNAKE_CASE	,				help="Save precision-recall curves to directory."				)
	parser.add_argument("--verbose"	,				"-v"	,				action="store_true"				)
	if len(sys.argv				) == 1:
		parser.print_help()
		sys.exit(1				)
	return parser.parse_args()


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[Any]				)     ->					Dict:


	"""simple docstring"""





	UpperCAmelCase_     :      Tuple						=  {}
	for article in dataset:
		for p in article["paragraphs"]:
			for qa in p["qas"]:
				UpperCAmelCase_     :      Dict						=  bool(qa["answers"]["text"]				)
	return qid_to_has_ans


def  a__       (    _SCREAMING_SNAKE_CASE   :       Union[str, Any]				)     ->					Any:


	"""simple docstring"""





	def remove_articles(_SCREAMING_SNAKE_CASE   :       Optional[int]				):
		return ARTICLES_REGEX.sub(" "	,				_SCREAMING_SNAKE_CASE				)

	def white_space_fix(_SCREAMING_SNAKE_CASE   :       Optional[int]				):
		return " ".join(text.split()				)

	def remove_punc(_SCREAMING_SNAKE_CASE   :       Optional[int]				):
		UpperCAmelCase_     :      Tuple						=  set(string.punctuation				)
		return "".join(ch for ch in text if ch not in exclude				)

	def lower(_SCREAMING_SNAKE_CASE   :       List[Any]				):
		return text.lower()

	return white_space_fix(remove_articles(remove_punc(lower(_SCREAMING_SNAKE_CASE				)				)				)				)


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[int]				)     ->					str:


	"""simple docstring"""





	if not s:
		return []
	return normalize_answer(_SCREAMING_SNAKE_CASE				).split()


def  a__       (    _SCREAMING_SNAKE_CASE   :       Any	,				_SCREAMING_SNAKE_CASE   :       List[str]				)     ->					Dict:


	"""simple docstring"""





	return int(normalize_answer(_SCREAMING_SNAKE_CASE				) == normalize_answer(_SCREAMING_SNAKE_CASE				)				)


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[int]	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]				)     ->					Optional[Any]:


	"""simple docstring"""





	UpperCAmelCase_     :      str						=  get_tokens(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Tuple						=  get_tokens(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      List[Any]						=  collections.Counter(_SCREAMING_SNAKE_CASE				) & collections.Counter(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Tuple						=  sum(common.values()				)
	if len(_SCREAMING_SNAKE_CASE				) == 0 or len(_SCREAMING_SNAKE_CASE				) == 0:
		# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
		return int(gold_toks == pred_toks				)
	if num_same == 0:
		return 0
	UpperCAmelCase_     :      Dict						=  1.0 * num_same / len(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Optional[int]						=  1.0 * num_same / len(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      List[str]						=  (2 * precision * recall) / (precision + recall)
	return fa


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]				)     ->					int:


	"""simple docstring"""





	UpperCAmelCase_     :      Tuple						=  {}
	UpperCAmelCase_     :      int						=  {}
	for article in dataset:
		for p in article["paragraphs"]:
			for qa in p["qas"]:
				UpperCAmelCase_     :      Union[str, Any]						=  qa["id"]
				UpperCAmelCase_     :      str						=  [t for t in qa["answers"]["text"] if normalize_answer(_SCREAMING_SNAKE_CASE				)]
				if not gold_answers:
					# For unanswerable questions, only correct answer is empty string
					UpperCAmelCase_     :      int						=  [""]
				if qid not in preds:
					print(F'''Missing prediction for {qid}'''				)
					continue
				UpperCAmelCase_     :      Dict						=  preds[qid]
				# Take max over all gold answers
				UpperCAmelCase_     :      Any						=  max(compute_exact(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				) for a in gold_answers				)
				UpperCAmelCase_     :      str						=  max(compute_fa(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				) for a in gold_answers				)
	return exact_scores, fa_scores


def  a__       (    _SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       Tuple	,				_SCREAMING_SNAKE_CASE   :       Tuple	,				_SCREAMING_SNAKE_CASE   :       str				)     ->					Tuple:


	"""simple docstring"""





	UpperCAmelCase_     :      int						=  {}
	for qid, s in scores.items():
		UpperCAmelCase_     :      Dict						=  na_probs[qid] > na_prob_thresh
		if pred_na:
			UpperCAmelCase_     :      Tuple						=  float(not qid_to_has_ans[qid]				)
		else:
			UpperCAmelCase_     :      Any						=  s
	return new_scores


def  a__       (    _SCREAMING_SNAKE_CASE   :       List[Any]	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]	,				_SCREAMING_SNAKE_CASE   :       Tuple=None				)     ->					int:


	"""simple docstring"""





	if not qid_list:
		UpperCAmelCase_     :      Union[str, Any]						=  len(_SCREAMING_SNAKE_CASE				)
		return collections.OrderedDict(
		    [
		        ("exact", 100.0 * sum(exact_scores.values()				) / total),
		        ("f1", 100.0 * sum(fa_scores.values()				) / total),
		        ("total", total),
		    ]				)
	else:
		UpperCAmelCase_     :      str						=  len(_SCREAMING_SNAKE_CASE				)
		return collections.OrderedDict(
		    [
		        ("exact", 100.0 * sum(exact_scores[k] for k in qid_list				) / total),
		        ("f1", 100.0 * sum(fa_scores[k] for k in qid_list				) / total),
		        ("total", total),
		    ]				)


def  a__       (    _SCREAMING_SNAKE_CASE   :       int	,				_SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]				)     ->					Any:


	"""simple docstring"""





	for k in new_eval:
		UpperCAmelCase_     :      int						=  new_eval[k]


def  a__       (    _SCREAMING_SNAKE_CASE   :       List[Any]	,				_SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       Optional[int]				)     ->					str:


	"""simple docstring"""





	plt.step(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				color="b"	,				alpha=0.2	,				where="post"				)
	plt.fill_between(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				step="post"	,				alpha=0.2	,				color="b"				)
	plt.xlabel("Recall"				)
	plt.ylabel("Precision"				)
	plt.xlim([0.0, 1.05]				)
	plt.ylim([0.0, 1.05]				)
	plt.title(_SCREAMING_SNAKE_CASE				)
	plt.savefig(_SCREAMING_SNAKE_CASE				)
	plt.clf()


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       Any	,				_SCREAMING_SNAKE_CASE   :       List[Any]	,				_SCREAMING_SNAKE_CASE   :       int=None	,				_SCREAMING_SNAKE_CASE   :       Optional[Any]=None				)     ->					Optional[int]:


	"""simple docstring"""





	UpperCAmelCase_     :      List[Any]						=  sorted(_SCREAMING_SNAKE_CASE	,				key=lambda _SCREAMING_SNAKE_CASE				: na_probs[k]				)
	UpperCAmelCase_     :      List[Any]						=  0.0
	UpperCAmelCase_     :      Dict						=  1.0
	UpperCAmelCase_     :      Union[str, Any]						=  0.0
	UpperCAmelCase_     :      Dict						=  [1.0]
	UpperCAmelCase_     :      List[str]						=  [0.0]
	UpperCAmelCase_     :      Any						=  0.0
	for i, qid in enumerate(_SCREAMING_SNAKE_CASE				):
		if qid_to_has_ans[qid]:
			true_pos += scores[qid]
		UpperCAmelCase_     :      Optional[Any]						=  true_pos / float(i + 1				)
		UpperCAmelCase_     :      Any						=  true_pos / float(_SCREAMING_SNAKE_CASE				)
		if i == len(_SCREAMING_SNAKE_CASE				) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
			# i.e., if we can put a threshold after this point
			avg_prec += cur_p * (cur_r - recalls[-1])
			precisions.append(_SCREAMING_SNAKE_CASE				)
			recalls.append(_SCREAMING_SNAKE_CASE				)
	if out_image:
		plot_pr_curve(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	return {"ap": 100.0 * avg_prec}


def  a__       (    _SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       List[Any]	,				_SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]	,				_SCREAMING_SNAKE_CASE   :       str	,				_SCREAMING_SNAKE_CASE   :       str				)     ->					Optional[Any]:


	"""simple docstring"""





	if out_image_dir and not os.path.exists(_SCREAMING_SNAKE_CASE				):
		os.makedirs(_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Dict						=  sum(1 for v in qid_to_has_ans.values() if v				)
	if num_true_pos == 0:
		return
	UpperCAmelCase_     :      Optional[int]						=  make_precision_recall_eval(
	    _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				out_image=os.path.join(_SCREAMING_SNAKE_CASE	,				"pr_exact.png"				)	,				title="Precision-Recall curve for Exact Match score"	,				)
	UpperCAmelCase_     :      Tuple						=  make_precision_recall_eval(
	    _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				out_image=os.path.join(_SCREAMING_SNAKE_CASE	,				"pr_f1.png"				)	,				title="Precision-Recall curve for F1 score"	,				)
	UpperCAmelCase_     :      Union[str, Any]						=  {k: float(_SCREAMING_SNAKE_CASE				) for k, v in qid_to_has_ans.items()}
	UpperCAmelCase_     :      Optional[int]						=  make_precision_recall_eval(
	    _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				out_image=os.path.join(_SCREAMING_SNAKE_CASE	,				"pr_oracle.png"				)	,				title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"	,				)
	merge_eval(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				"pr_exact"				)
	merge_eval(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				"pr_f1"				)
	merge_eval(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				"pr_oracle"				)


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       List[str]	,				_SCREAMING_SNAKE_CASE   :       Tuple	,				_SCREAMING_SNAKE_CASE   :       int				)     ->					List[Any]:


	"""simple docstring"""





	if not qid_list:
		return
	UpperCAmelCase_     :      List[Any]						=  [na_probs[k] for k in qid_list]
	UpperCAmelCase_     :      Dict						=  np.ones_like(_SCREAMING_SNAKE_CASE				) / float(len(_SCREAMING_SNAKE_CASE				)				)
	plt.hist(_SCREAMING_SNAKE_CASE	,				weights=_SCREAMING_SNAKE_CASE	,				bins=20	,				range=(0.0, 1.0)				)
	plt.xlabel("Model probability of no-answer"				)
	plt.ylabel("Proportion of dataset"				)
	plt.title(F'''Histogram of no-answer probability: {name}'''				)
	plt.savefig(os.path.join(_SCREAMING_SNAKE_CASE	,				F'''na_prob_hist_{name}.png'''				)				)
	plt.clf()


def  a__       (    _SCREAMING_SNAKE_CASE   :       Any	,				_SCREAMING_SNAKE_CASE   :       Tuple	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]	,				_SCREAMING_SNAKE_CASE   :       Optional[Any]				)     ->					Dict:


	"""simple docstring"""





	UpperCAmelCase_     :      Optional[int]						=  sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]				)
	UpperCAmelCase_     :      List[str]						=  num_no_ans
	UpperCAmelCase_     :      Optional[int]						=  cur_score
	UpperCAmelCase_     :      Any						=  0.0
	UpperCAmelCase_     :      List[str]						=  sorted(_SCREAMING_SNAKE_CASE	,				key=lambda _SCREAMING_SNAKE_CASE				: na_probs[k]				)
	for i, qid in enumerate(_SCREAMING_SNAKE_CASE				):
		if qid not in scores:
			continue
		if qid_to_has_ans[qid]:
			UpperCAmelCase_     :      Tuple						=  scores[qid]
		else:
			if preds[qid]:
				UpperCAmelCase_     :      int						=  -1
			else:
				UpperCAmelCase_     :      Optional[int]						=  0
		cur_score += diff
		if cur_score > best_score:
			UpperCAmelCase_     :      int						=  cur_score
			UpperCAmelCase_     :      Tuple						=  na_probs[qid]
	return 100.0 * best_score / len(_SCREAMING_SNAKE_CASE				), best_thresh


def  a__       (    _SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       Optional[Any]	,				_SCREAMING_SNAKE_CASE   :       Tuple	,				_SCREAMING_SNAKE_CASE   :       Union[str, Any]	,				_SCREAMING_SNAKE_CASE   :       Optional[int]	,				_SCREAMING_SNAKE_CASE   :       str				)     ->					int:


	"""simple docstring"""





	UpperCAmelCase_					,					UpperCAmelCase_     :      List[Any]						=  find_best_thresh(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_					,					UpperCAmelCase_     :      int						=  find_best_thresh(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Optional[Any]						=  best_exact
	UpperCAmelCase_     :      int						=  exact_thresh
	UpperCAmelCase_     :      int						=  best_fa
	UpperCAmelCase_     :      Union[str, Any]						=  fa_thresh


def  a__       (    )     ->					str:


	"""simple docstring"""





	with open(OPTS.data_file				) as f:
		UpperCAmelCase_     :      Union[str, Any]						=  json.load(_SCREAMING_SNAKE_CASE				)
		UpperCAmelCase_     :      Union[str, Any]						=  dataset_json["data"]
	with open(OPTS.pred_file				) as f:
		UpperCAmelCase_     :      int						=  json.load(_SCREAMING_SNAKE_CASE				)
	if OPTS.na_prob_file:
		with open(OPTS.na_prob_file				) as f:
			UpperCAmelCase_     :      Dict						=  json.load(_SCREAMING_SNAKE_CASE				)
	else:
		UpperCAmelCase_     :      List[Any]						=  {k: 0.0 for k in preds}
	UpperCAmelCase_     :      Tuple						=  make_qid_to_has_ans(_SCREAMING_SNAKE_CASE				)  # maps qid to True/False
	UpperCAmelCase_     :      Dict						=  [k for k, v in qid_to_has_ans.items() if v]
	UpperCAmelCase_     :      Dict						=  [k for k, v in qid_to_has_ans.items() if not v]
	UpperCAmelCase_					,					UpperCAmelCase_     :      Optional[int]						=  get_raw_scores(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	UpperCAmelCase_     :      Optional[int]						=  apply_no_ans_threshold(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				OPTS.na_prob_thresh				)
	UpperCAmelCase_     :      Dict						=  apply_no_ans_threshold(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				OPTS.na_prob_thresh				)
	UpperCAmelCase_     :      Optional[int]						=  make_eval_dict(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	if has_ans_qids:
		UpperCAmelCase_     :      Optional[Any]						=  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:
		UpperCAmelCase_     :      Any						=  make_eval_dict(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				qid_list=_SCREAMING_SNAKE_CASE				)
		merge_eval(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				"NoAns"				)
	if OPTS.na_prob_file:
		find_all_best_thresh(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	if OPTS.na_prob_file and OPTS.out_image_dir:
		run_precision_recall_analysis(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				OPTS.out_image_dir				)
		histogram_na_prob(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				OPTS.out_image_dir	,				"hasAns"				)
		histogram_na_prob(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				OPTS.out_image_dir	,				"noAns"				)
	if OPTS.out_file:
		with open(OPTS.out_file	,				"w"				) as f:
			json.dump(_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE				)
	else:
		print(json.dumps(_SCREAMING_SNAKE_CASE	,				indent=2				)				)


if __name__ == "__main__":
					_lowerCamelCase      					=     parse_args()
					if OPTS.out_image_dir:
										import matplotlib

										matplotlib.use("""Agg""")
										import matplotlib.pyplot as plt
					main()







import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
    import torch
    from torch import nn

    from transformers import SwiftFormerForImageClassification, SwiftFormerModel
    from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor





class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




   def __init__(       self					:			List[str]     , __lowerCamelCase					:			int     , __lowerCamelCase					:			int=13     , __lowerCamelCase					:			Optional[int]=3     , __lowerCamelCase					:			str=True     , __lowerCamelCase					:			Any=True     , __lowerCamelCase					:			Optional[Any]=0.1     , __lowerCamelCase					:			Any=0.1     , __lowerCamelCase					:			Optional[int]=224     , __lowerCamelCase					:			Any=1000     , __lowerCamelCase					:			Optional[Any]=[3, 3, 6, 4]     , __lowerCamelCase					:			List[Any]=[48, 56, 112, 220]     , ):
       SCREAMING_SNAKE_CASE										=   parent
       SCREAMING_SNAKE_CASE										=   batch_size
       SCREAMING_SNAKE_CASE										=   num_channels
       SCREAMING_SNAKE_CASE										=   is_training
       SCREAMING_SNAKE_CASE										=   use_labels
       SCREAMING_SNAKE_CASE										=   hidden_dropout_prob
       SCREAMING_SNAKE_CASE										=   attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE										=   num_labels
       SCREAMING_SNAKE_CASE										=   image_size
       SCREAMING_SNAKE_CASE										=   layer_depths
       SCREAMING_SNAKE_CASE										=   embed_dims





   def      _snake_case		(       self					:			Optional[Any]			):
       SCREAMING_SNAKE_CASE										=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

       SCREAMING_SNAKE_CASE										=   None
       if self.use_labels:
           SCREAMING_SNAKE_CASE										=   ids_tensor([self.batch_size]     , self.num_labels			)

       SCREAMING_SNAKE_CASE										=   self.get_config()

       return config, pixel_values, labels





   def      _snake_case		(       self					:			Dict			):
       return SwiftFormerConfig(
           depths=self.layer_depths     , embed_dims=self.embed_dims     , mlp_ratio=4     , downsamples=[True, True, True, True]     , hidden_act="gelu"     , num_labels=self.num_labels     , down_patch_size=3     , down_stride=2     , down_pad=1     , drop_rate=0.0     , drop_path_rate=0.0     , use_layer_scale=__lowerCamelCase     , layer_scale_init_value=1e-5     , )





   def      _snake_case		(       self					:			List[str]     , __lowerCamelCase					:			Union[str, Any]     , __lowerCamelCase					:			Tuple     , __lowerCamelCase					:			List[Any]			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerModel(config=__lowerCamelCase			)
       model.to(__lowerCamelCase			)
       model.eval()
       SCREAMING_SNAKE_CASE										=   model(__lowerCamelCase			)
       self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.embed_dims[-1], 7, 7)			)





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			int     , __lowerCamelCase					:			Any     , __lowerCamelCase					:			Optional[int]			):
       SCREAMING_SNAKE_CASE										=   self.num_labels
       SCREAMING_SNAKE_CASE										=   SwiftFormerForImageClassification(__lowerCamelCase			)
       model.to(__lowerCamelCase			)
       model.eval()
       SCREAMING_SNAKE_CASE										=   model(__lowerCamelCase     , labels=__lowerCamelCase			)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)			)

       SCREAMING_SNAKE_CASE										=   SwiftFormerForImageClassification(__lowerCamelCase			)
       model.to(__lowerCamelCase			)
       model.eval()

       SCREAMING_SNAKE_CASE										=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)
       SCREAMING_SNAKE_CASE										=   model(__lowerCamelCase			)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)			)





   def      _snake_case		(       self					:			int			):
       ((SCREAMING_SNAKE_CASE)							,	(SCREAMING_SNAKE_CASE)							,	(SCREAMING_SNAKE_CASE))										=   self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE										=   {"pixel_values": pixel_values}
       return config, inputs_dict





@require_torch
class 			_SCREAMING_SNAKE_CASE (   __snake_case					,       __snake_case					,       unittest.TestCase		):







   '''simple docstring'''




   lowerCamelCase__				=      (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
   lowerCamelCase__				=      (
       {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
       if is_torch_available()
       else {}
   )

   lowerCamelCase__				=      False
   lowerCamelCase__				=      False
   lowerCamelCase__				=      False
   lowerCamelCase__				=      False
   lowerCamelCase__				=      False





   def      _snake_case		(       self					:			int			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerModelTester(self			)
       SCREAMING_SNAKE_CASE										=   ConfigTester(
           self     , config_class=__lowerCamelCase     , has_text_modality=__lowerCamelCase     , hidden_size=37     , num_attention_heads=12     , num_hidden_layers=12     , )





   def      _snake_case		(       self					:			List[Any]			):
       self.config_tester.run_common_tests()





   @unittest.skip(reason="SwiftFormer does not use inputs_embeds"			)
   def      _snake_case		(       self					:			Optional[int]			):
       pass





   def      _snake_case		(       self					:			Optional[int]			):
       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   model_class(__lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(__lowerCamelCase     , nn.Linear			)			)





   def      _snake_case		(       self					:			List[Any]			):
       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   model_class(__lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   inspect.signature(model.forward			)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           SCREAMING_SNAKE_CASE										=   [*signature.parameters.keys()]

           SCREAMING_SNAKE_CASE										=   ["pixel_values"]
           self.assertListEqual(arg_names[:1]     , __lowerCamelCase			)





   def      _snake_case		(       self					:			Union[str, Any]			):
       SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase			)





   def      _snake_case		(       self					:			int			):
       SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)





   @slow
   def      _snake_case		(       self					:			Tuple			):
       for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           SCREAMING_SNAKE_CASE										=   SwiftFormerModel.from_pretrained(__lowerCamelCase			)
           self.assertIsNotNone(__lowerCamelCase			)





   @unittest.skip(reason="SwiftFormer does not output attentions"			)
   def      _snake_case		(       self					:			Union[str, Any]			):
       pass





   def      _snake_case		(       self					:			Optional[Any]			):
       def check_hidden_states_output(__lowerCamelCase					:			Optional[int]     , __lowerCamelCase					:			str     , __lowerCamelCase					:			Tuple			):
           SCREAMING_SNAKE_CASE										=   model_class(__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()

           with torch.no_grad():
               SCREAMING_SNAKE_CASE										=   model(**self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase			)			)

           SCREAMING_SNAKE_CASE										=   outputs.hidden_states

           SCREAMING_SNAKE_CASE										=   8
           self.assertEqual(len(__lowerCamelCase			)     , __lowerCamelCase			)  # TODO

           # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
           # with the width and height being successively divided by 2, after every 2 blocks
           for i in range(len(__lowerCamelCase			)			):
               self.assertEqual(
                   hidden_states[i].shape     , torch.Size(
                       [
                           self.model_tester.batch_size,
                           self.model_tester.embed_dims[i // 2],
                           (self.model_tester.image_size // 4) // 2 ** (i // 2),
                           (self.model_tester.image_size // 4) // 2 ** (i // 2),
                       ]			)     , )

       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   True
           check_hidden_states_output(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           SCREAMING_SNAKE_CASE										=   True

           check_hidden_states_output(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)





   def      _snake_case		(       self					:			List[Any]			):
       def _config_zero_init(__lowerCamelCase					:			List[Any]			):
           SCREAMING_SNAKE_CASE										=   copy.deepcopy(__lowerCamelCase			)
           for key in configs_no_init.__dict__.keys():
               if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
                   setattr(__lowerCamelCase     , __lowerCamelCase     , 1e-10			)
               if isinstance(getattr(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)     , __lowerCamelCase			):
                   SCREAMING_SNAKE_CASE										=   _config_zero_init(getattr(__lowerCamelCase     , __lowerCamelCase			)			)
                   setattr(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)
           return configs_no_init

       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE										=   _config_zero_init(__lowerCamelCase			)
       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   model_class(config=__lowerCamelCase			)
           for name, param in model.named_parameters():
               if param.requires_grad:
                   self.assertIn(
                       ((param.data.mean() * 1e9) / 1e9).round().item()     , [0.0, 1.0]     , msg=f"Parameter {name} of model {model_class} seems not properly initialized"     , )





   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."			)
   def      _snake_case		(       self					:			str			):
       pass





def 	__a     (      ):
    SCREAMING_SNAKE_CASE										=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
    return image





@require_torch
@require_vision
class 			_SCREAMING_SNAKE_CASE (   unittest.TestCase		):







   '''simple docstring'''




   @cached_property
   def      _snake_case		(       self					:			List[str]			):
       return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs"			) if is_vision_available() else None





   @slow
   def      _snake_case		(       self					:			List[Any]			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs"			).to(__lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   self.default_image_processor
       SCREAMING_SNAKE_CASE										=   prepare_img()
       SCREAMING_SNAKE_CASE										=   image_processor(images=__lowerCamelCase     , return_tensors="pt"			).to(__lowerCamelCase			)

       # forward pass
       with torch.no_grad():
           SCREAMING_SNAKE_CASE										=   model(**__lowerCamelCase			)

       # verify the logits
       SCREAMING_SNAKE_CASE										=   torch.Size((1, 1000)			)
       self.assertEqual(outputs.logits.shape     , __lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]]			).to(__lowerCamelCase			)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]     , __lowerCamelCase     , atol=1e-4			)			)