


"""simple docstring"""






import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union


class 			SCREAMING_SNAKE_CASE_  (   enum.Enum):




							'''simple docstring'''





							__magic_name__					:     str				  =  '''timm'''
							__magic_name__					:     Any				  =  '''transformers'''



def 			A__		(					_UpperCAmelCase    :      Optional[Iterable[str]]				,    _UpperCAmelCase    :      Optional[Iterable[int]]				,    _UpperCAmelCase    :      Optional[Iterable[str]]	)							->	Tuple:

	'''simple docstring'''


	if stage_names is None:
		raise ValueError("Stage_names must be set for transformers backbones"	)

	if out_features is not None:
		if not isinstance(lowerCamelCase__				,    (list,)	):
			raise ValueError(F"""out_features must be a list {type(lowerCamelCase__	)}"""	)
		if any(feat not in stage_names for feat in out_features	):
			raise ValueError(F"""out_features must be a subset of stage_names: {stage_names} got {out_features}"""	)

	if out_indices is not None:
		if not isinstance(lowerCamelCase__				,    (list, tuple)	):
			raise ValueError(F"""out_indices must be a list or tuple, got {type(lowerCamelCase__	)}"""	)
		if any(idx >= len(lowerCamelCase__	) for idx in out_indices	):
			raise ValueError("out_indices must be valid indices for stage_names {stage_names}, got {out_indices}"	)

	if out_features is not None and out_indices is not None:
		if len(lowerCamelCase__	) != len(lowerCamelCase__	):
			raise ValueError("out_features and out_indices should have the same length if both are set"	)
		if out_features != [stage_names[idx] for idx in out_indices]:
			raise ValueError("out_features and out_indices should correspond to the same stages if both are set"	)



def 			A__		(					_UpperCAmelCase    :      Optional[List[str]]				,    _UpperCAmelCase    :      Optional[Union[List[int], Tuple[int]]]				,    _UpperCAmelCase    :      List[str]				,    )							->	List[str]:

	'''simple docstring'''


	if out_indices is None and out_features is None:
		snake_case__  :						Optional[Any]		=      [len(lowerCamelCase__	) - 1]
		snake_case__  :						Dict		=      [stage_names[-1]]
	elif out_indices is None and out_features is not None:
		snake_case__  :						Optional[Any]		=      [stage_names.index(lowerCamelCase__	) for layer in out_features]
	elif out_features is None and out_indices is not None:
		snake_case__  :						Union[str, Any]		=      [stage_names[idx] for idx in out_indices]
	return out_features, out_indices



def 			A__		(					_UpperCAmelCase    :      Optional[List[str]]				,    _UpperCAmelCase    :      Optional[Union[List[int], Tuple[int]]]				,    _UpperCAmelCase    :      List[str]				,    )							->	Tuple[List[str], List[int]]:

	'''simple docstring'''


	verify_out_features_out_indices(out_features=lowerCamelCase__				,    out_indices=lowerCamelCase__				,    stage_names=lowerCamelCase__	)
	snake_case__  :						Dict		=      _align_output_features_output_indices(
	    out_features=lowerCamelCase__				,    out_indices=lowerCamelCase__				,    stage_names=lowerCamelCase__	)
	# Verify that the aligned out_features and out_indices are valid
	verify_out_features_out_indices(out_features=lowerCamelCase__				,    out_indices=lowerCamelCase__				,    stage_names=lowerCamelCase__	)
	return output_features, output_indices


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							__magic_name__					:     List[str]				  =  None




							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	Optional[Any]:







								'''simple docstring'''




								if getattr(self	,					"_backbone"	,					_lowerCamelCase) is None:
									raise ValueError("self._backbone must be set before calling _init_timm_backbone")

								# These will diagree with the defaults for the transformers models e.g. for resnet50
								# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
								# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
								snake_case__  :						Union[str, Any]		=      [stage['''module'''] for stage in self._backbone.feature_info.info]
								snake_case__  :						List[Any]		=      [stage['''num_chs'''] for stage in self._backbone.feature_info.info]
								snake_case__  :						int		=      self._backbone.feature_info.out_indices
								snake_case__  :						Union[str, Any]		=      self._backbone.feature_info.module_name()

								# We verify the out indices and out features are valid
								verify_out_features_out_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=self.stage_names)
								snake_case__  :						Optional[int]		=      out_features, out_indices




							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      getattr(_lowerCamelCase	,					"stage_names")
								snake_case__  :						str		=      getattr(_lowerCamelCase	,					"out_features"	,					_lowerCamelCase)
								snake_case__  :						Tuple		=      getattr(_lowerCamelCase	,					"out_indices"	,					_lowerCamelCase)

								snake_case__  :						Union[str, Any]		=      stage_names
								snake_case__  :						Tuple		=      get_aligned_output_features_output_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=_lowerCamelCase)
								# Number of channels for each stage. This is set in the transformer backbone model init
								snake_case__  :						Tuple		=      None




							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	Tuple:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      config

								snake_case__  :						Union[str, Any]		=      getattr(_lowerCamelCase	,					"use_timm_backbone"	,					_lowerCamelCase)
								snake_case__  :						Tuple		=      BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

								if self.backbone_type == BackboneType.TIMM:
									self._init_timm_backbone(_lowerCamelCase)
								elif self.backbone_type == BackboneType.TRANSFORMERS:
									self._init_transformers_backbone(_lowerCamelCase)
								else:
									raise ValueError(f"""backbone_type {self.backbone_type} not supported.""")




							@property
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								return self._out_features




							@out_features.setter
							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	Any:







								'''simple docstring'''




								snake_case__  :						Tuple		=      get_aligned_output_features_output_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=self.stage_names)




							@property
							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								return self._out_indices




							@out_indices.setter
							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	int:







								'''simple docstring'''




								snake_case__  :						Tuple		=      get_aligned_output_features_output_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=self.stage_names)




							@property
							def        UpperCAmelCase (						self)   ->	int:







								'''simple docstring'''




								return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names)}




							@property
							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								return [self.out_feature_channels[name] for name in self.out_features]




							def        UpperCAmelCase (						self	,					*lowerCamelCase__	,					**lowerCamelCase__)   ->	List[Any]:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      dict(inspect.signature(self.forward).parameters)
								snake_case__  :						str		=      {k: v for k, v in kwargs.items() if k in signature}
								return self(*_lowerCamelCase	,					**_lowerCamelCase)




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__ = None	,					lowerCamelCase__ = None	,					lowerCamelCase__ = None	,					)   ->	Any:







								'''simple docstring'''




								raise NotImplementedError("This method should be implemented by the derived class.")







							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      super().to_dict()
								snake_case__  :						Union[str, Any]		=      output.pop("_out_features")
								snake_case__  :						Optional[Any]		=      output.pop("_out_indices")
								return output


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							@property
							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								return self._out_features




							@out_features.setter
							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      get_aligned_output_features_output_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=self.stage_names)




							@property
							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								return self._out_indices




							@out_indices.setter
							def        UpperCAmelCase (						self	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								snake_case__  :						List[str]		=      get_aligned_output_features_output_indices(
								    out_features=_lowerCamelCase	,					out_indices=_lowerCamelCase	,					stage_names=self.stage_names)







							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      super().to_dict()
								snake_case__  :						Optional[Any]		=      output.pop("_out_features")
								snake_case__  :						Tuple		=      output.pop("_out_indices")
								return output











'''simple docstring'''




import jax
import jax.numpy as jnp
from bigbird_flax import FlaxBigBirdForNaturalQuestions
from datasets import load_from_disk

from transformers import BigBirdTokenizerFast


snake_case__ 							=    {0: """null""", 1: """short""", 2: """long""", 3: """yes""", 4: """no"""}
snake_case__ 							=    set("""""".join(["""‘""", """’""", """´""", """`""", """.""", """,""", """-""", """\""""]))




def     snake_case__     (			lowerCamelCase__					: List[str]      ,		lowerCamelCase__					: Tuple=0      ,		lowerCamelCase__					: Tuple=None      ) -> Optional[Any]:
					return [" ".join(x.split(''' '''      )[begin:end]      ) for x in answers if len(x.split(''' '''      )      ) > 1]




def     snake_case__     (			lowerCamelCase__					: Any      ,		lowerCamelCase__					: Any=False      ) -> List[Any]:
					if make_sub_answers:
										# if answers are longer than one word, make sure a predictions is correct if it coresponds to the complete 1: or :-1 sub word
										# *e.g.* if the correct answer contains a prefix such as "the", or "a"
										A_			:  Union[str, Any]			=				(
										    given_answers + get_sub_answers(lowerCamelCase__      ,		begin=1      ) + get_sub_answers(lowerCamelCase__      ,		end=-1      )
										)
					A_			:  List[Any]			=				[]
					for answer in given_answers:
										A_			:  Dict			=				answer.replace('''_'''      ,		''' '''      ).lower()
										A_			:  str			=				''''''.join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else ''' ''' for c in alias      )
										answers.append(''' '''.join(alias.split()      ).strip()      )
					return set(lowerCamelCase__      )




def     snake_case__     (			lowerCamelCase__					: Optional[Any]      ,		lowerCamelCase__					: Dict      ,		lowerCamelCase__					: Union[str, Any]=1      ,		lowerCamelCase__					: Any=1_0_0      ) -> Any:
					A_			,A_			:  str			=				jax.lax.top_k(lowerCamelCase__      ,		lowerCamelCase__      )
					A_			,A_			:  str			=				jax.lax.top_k(lowerCamelCase__      ,		lowerCamelCase__      )

					A_			:  List[Any]			=				best_end_idx[:, None] - best_start_idx[None, :]
					A_			:  Optional[Any]			=				jnp.logical_or(widths < 0      ,		widths > max_size      )
					A_			:  Optional[int]			=				(best_end_scores[:, None] + best_start_scores[None, :]) - (1e8 * mask)
					A_			:  str			=				jnp.argmax(lowerCamelCase__      ).item()

					return best_start_idx[best_score % top_k], best_end_idx[best_score // top_k]




def     snake_case__     (			lowerCamelCase__					: List[str]      ) -> Union[str, Any]:
					A_			:  str			=				sample['''question''']['''text''']
					A_			:  Tuple			=				sample['''document''']['''tokens''']['''token''']
					A_			:  List[Any]			=				sample['''document''']['''tokens''']['''is_html''']
					A_			:  Tuple			=				sample['''annotations''']['''long_answer''']
					A_			:  List[Any]			=				sample['''annotations''']['''short_answers''']

					A_			:  Optional[Any]			=				''' '''.join([context[i] for i in range(len(lowerCamelCase__      )      ) if not is_html[i]]      )

					# 0 - No ; 1 - Yes
					for answer in sample["annotations"]["yes_no_answer"]:
										if answer == 0 or answer == 1:
															return {
															    "question": question,
															    "context": context_string,
															    "short": [],
															    "long": [],
															    "category": "no" if answer == 0 else "yes",
															}

					A_			:  List[Any]			=				[]
					for s in short_answers:
										short_targets.extend(s['''text''']      )
					A_			:  Tuple			=				list(set(lowerCamelCase__      )      )

					A_			:  Tuple			=				[]
					for s in long_answers:
										if s["start_token"] == -1:
															continue
										A_			:  Dict			=				context[s['''start_token'''] : s['''end_token''']]
										A_			:  Tuple			=				is_html[s['''start_token'''] : s['''end_token''']]
										A_			:  Optional[Any]			=				''' '''.join([answer[i] for i in range(len(lowerCamelCase__      )      ) if not html[i]]      )
										if new_answer not in long_targets:
															long_targets.append(lowerCamelCase__      )

					A_			:  str			=				'''long_short''' if len(short_targets + long_targets      ) > 0 else '''null'''

					return {
					    "question": question,
					    "context": context_string,
					    "short": short_targets,
					    "long": long_targets,
					    "category": category,
					}




def     snake_case__     (			) -> List[Any]:
					A_			:  int			=				load_from_disk('''natural-questions-validation'''      )
					A_			:  Optional[int]			=				dataset.map(lowerCamelCase__      ).remove_columns(['''annotations''', '''document''', '''id''']      )
					print(lowerCamelCase__      )

					A_			:  Tuple			=				dataset.filter(lambda lowerCamelCase__      : (len(x['''question''']      ) + len(x['''context''']      )) < 4 * 4_0_9_6      )
					A_			:  Optional[Any]			=				short_validation_dataset.filter(lambda lowerCamelCase__      : x["category"] != "null"      )
					short_validation_dataset

					A_			:  Union[str, Any]			=				'''vasudevgupta/flax-bigbird-natural-questions'''
					A_			:  List[str]			=				FlaxBigBirdForNaturalQuestions.from_pretrained(lowerCamelCase__      )
					A_			:  int			=				BigBirdTokenizerFast.from_pretrained(lowerCamelCase__      )

					@jax.jit
					def forward(*lowerCamelCase__					: Any      ,		**lowerCamelCase__					: Optional[Any]      ):
										A_			,A_			,A_			:  Tuple			=				model(*lowerCamelCase__      ,		**lowerCamelCase__      )
										return start_logits, end_logits, jnp.argmax(lowerCamelCase__      ,		axis=-1      )

					def evaluate(lowerCamelCase__					: List[str]      ):
										# encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
										A_			:  List[Any]			=				tokenizer(
										    example['''question''']      ,		example['''context''']      ,		return_tensors='''np'''      ,		max_length=4_0_9_6      ,		padding='''max_length'''      ,		truncation=lowerCamelCase__      ,		)

										A_			,A_			,A_			:  Optional[Any]			=				forward(**lowerCamelCase__      )

										A_			:  Optional[Any]			=				CATEGORY_MAPPING[category.item()]

										A_			:  str			=				example['''long'''] + example['''short''']
										if example["category"] in ["yes", "no", "null"]:
															A_			:  str			=				[example['''category''']]
										A_			:  Optional[Any]			=				example['''category'''] != '''null'''
										# Now target can be: "yes", "no", "null", "list of long & short answers"

										if predicted_category in ["yes", "no", "null"]:
															A_			:  int			=				[predicted_category]
															A_			:  Optional[int]			=				example['''output'''] == example['''targets''']
															A_			:  Dict			=				predicted_category != '''null'''
															return example

										A_			:  List[Any]			=				3_8 if predicted_category == '''short''' else 1_0_2_4
										A_			,A_			:  str			=				get_best_valid_start_end_idx(
										    start_scores[0]      ,		end_scores[0]      ,		top_k=8      ,		max_size=lowerCamelCase__      )

										A_			:  List[Any]			=				inputs['''input_ids'''][0].tolist()
										A_			:  Dict			=				[tokenizer.decode(input_ids[start_score : end_score + 1]      )]

										A_			:  Optional[int]			=				expand_to_aliases(example['''targets''']      ,		make_sub_answers=lowerCamelCase__      )
										A_			:  str			=				expand_to_aliases(example['''output''']      )

										# some preprocessing to both prediction and answer
										A_			:  Tuple			=				{''''''.join(a.split()      ) for a in answers}
										A_			:  Optional[int]			=				{''''''.join(p.split()      ) for p in predictions}
										A_			:  List[str]			=				{s for s in predictions if s not in ['''``''', '''\'\'''', '''`''', '''\'''']}

										# if there is a common element, it's a exact match
										A_			:  List[Any]			=				len(list(answers & predictions      )      ) > 0
										A_			:  Dict			=				predicted_category != '''null''' and len(lowerCamelCase__      ) > 0

										return example

					A_			:  Dict			=				short_validation_dataset.map(lowerCamelCase__      )

					A_			:  List[str]			=				len(lowerCamelCase__      )
					A_			:  Any			=				len(short_validation_dataset.filter(lambda lowerCamelCase__      : x["match"] == 1      )      )
					print('''EM score:'''      ,		(matched / total) * 1_0_0      ,		'''%'''      )


if __name__ == "__main__":
							main()



