"""simple docstring"""






import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
						import torch

						lowerCAmelCase__    :    str			=      True
except ImportError:
						lowerCAmelCase__    :    Tuple			=      False


try:
						from torch.hub import _get_torch_home

						lowerCAmelCase__    :    Tuple			=      _get_torch_home()
except ImportError:
						lowerCAmelCase__    :    Union[str, Any]			=      os.path.expanduser(
						    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
						)

lowerCAmelCase__    :    Optional[Any]			=      os.path.join(torch_cache_home, 'transformers')

lowerCAmelCase__    :    List[str]			=      'https://cdn.huggingface.co'
lowerCAmelCase__    :    Optional[Any]			=      'https://s3.amazonaws.com/models.huggingface.co/bert'
lowerCAmelCase__    :    Any			=      '/'.join(str(Path(__file__).resolve()).split('/')[:-1])
lowerCAmelCase__    :    List[Any]			=      os.path.join(PATH, 'config.yaml')
lowerCAmelCase__    :    str			=      os.path.join(PATH, 'attributes.txt')
lowerCAmelCase__    :    str			=      os.path.join(PATH, 'objects.txt')
lowerCAmelCase__    :    Optional[Any]			=      os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
lowerCAmelCase__    :    Any			=      os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
lowerCAmelCase__    :    str			=      os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
lowerCAmelCase__    :    Tuple			=      'pytorch_model.bin'
lowerCAmelCase__    :    Dict			=      'config.yaml'



def     a_		(   lowerCamelCase=OBJECTS   ,     lowerCamelCase=ATTRIBUTES			):
				UpperCAmelCase__			 =				[]
				with open(lowerCamelCase_			) as f:
								for object in f.readlines():
												vg_classes.append(object.split(','			)[0].lower().strip()			)

				UpperCAmelCase__			 =				[]
				with open(lowerCamelCase_			) as f:
								for object in f.readlines():
												vg_attrs.append(object.split(','			)[0].lower().strip()			)
				return vg_classes, vg_attrs



def     a_		(   lowerCamelCase			):
				UpperCAmelCase__			 =				OrderedDict()
				with open(lowerCamelCase_   ,     'rb'			) as f:
								UpperCAmelCase__			 =				pkl.load(lowerCamelCase_			)['model']
				for k in copy.deepcopy(list(ckp.keys()			)			):
								UpperCAmelCase__			 =				ckp.pop(lowerCamelCase_			)
								if isinstance(lowerCamelCase_   ,     np.ndarray			):
												UpperCAmelCase__			 =				torch.tensor(lowerCamelCase_			)
								else:
												assert isinstance(lowerCamelCase_   ,     torch.tensor			), type(lowerCamelCase_			)
								UpperCAmelCase__			 =				v
				return r
class 							snake_case			:




					"""simple docstring"""

					snake_case__							       =					{}







					def __init__(							self  :      Union[str, Any]       ,lowerCamelCase__  :      dict       ,lowerCamelCase__  :      str = "root"       ,lowerCamelCase__  :      Optional[Any]=0     ):
									UpperCAmelCase__			 =				name
									UpperCAmelCase__			 =				level
									UpperCAmelCase__			 =				{}
									for k, v in dictionary.items():
													if v is None:
																	raise ValueError()
													UpperCAmelCase__			 =				copy.deepcopy(__A     )
													UpperCAmelCase__			 =				copy.deepcopy(__A     )
													if isinstance(__A       ,__A     ):
																	UpperCAmelCase__			 =				Config(__A       ,name=__A       ,level=level + 1     )
													UpperCAmelCase__			 =				v
													setattr(self       ,__A       ,__A     )

									UpperCAmelCase__			 =				d







					def __repr__(							self  :      int     ):
									return str(list((self._pointer.keys())     )     )







					def __setattr__(							self  :      List[Any]       ,lowerCamelCase__  :      Optional[int]       ,lowerCamelCase__  :      Optional[int]     ):
									UpperCAmelCase__			 =				val
									UpperCAmelCase__			 =				val
									UpperCAmelCase__			 =				key.split('.'     )
									UpperCAmelCase__			 =				len(__A     ) - 1
									UpperCAmelCase__			 =				self._pointer
									if len(__A     ) > 1:
													for i, l in enumerate(__A     ):
																	if hasattr(self       ,__A     ) and isinstance(getattr(self       ,__A     )       ,__A     ):
																					setattr(getattr(self       ,__A     )       ,'.'.join(levels[i:]     )       ,__A     )
																	if l == last_level:
																					UpperCAmelCase__			 =				val
																	else:
																					UpperCAmelCase__			 =				pointer[l]







					def 						__lowerCAmelCase		(							self  :      int     ):
									return self._pointer







					def 						__lowerCAmelCase		(							self  :      Any       ,lowerCamelCase__  :      List[Any]       ,lowerCamelCase__  :      Union[str, Any]     ):

									with open(f'''{file_name}'''       ,'w'     ) as stream:
													dump(__A       ,__A     )







					def 						__lowerCAmelCase		(							self  :      List[Any]       ,lowerCamelCase__  :      Optional[Any]       ,lowerCamelCase__  :      int     ):

									with open(f'''{file_name}'''       ,'w'     ) as stream:
													json.dump(__A       ,__A     )







					@staticmethod
					def 						__lowerCAmelCase		(							lowerCamelCase__  :      List[str]     ):

									with open(__A     ) as stream:
													UpperCAmelCase__			 =				load(__A       ,Loader=__A     )
									return data







					def __str__(							self  :      Any     ):
									UpperCAmelCase__			 =				'    '
									if self._name != "root":
													UpperCAmelCase__			 =				f'''{t * (self._level-1)}{self._name}:\n'''
									else:
													UpperCAmelCase__			 =				''
									UpperCAmelCase__			 =				self._level
									for i, (k, v) in enumerate(self._pointer.items()     ):
													if isinstance(__A       ,__A     ):
																	r += f'''{t * (self._level)}{v}\n'''
																	self._level += 1
													else:
																	r += f'''{t * (self._level)}{k}: {v} ({type(__A     ).__name__})\n'''
													UpperCAmelCase__			 =				level
									return r[:-1]







					@classmethod
					def 						__lowerCAmelCase		(							cls  :      int       ,lowerCamelCase__  :      str       ,**lowerCamelCase__  :      Any     ):
									UpperCAmelCase__ ,      UpperCAmelCase__			 =				cls.get_config_dict(__A       ,**__A     )
									return cls(__A     )







					@classmethod
					def 						__lowerCAmelCase		(							cls  :      Any       ,lowerCamelCase__  :      str       ,**lowerCamelCase__  :      List[str]     ):
									UpperCAmelCase__			 =				kwargs.pop('cache_dir'       ,__A     )
									UpperCAmelCase__			 =				kwargs.pop('force_download'       ,__A     )
									UpperCAmelCase__			 =				kwargs.pop('resume_download'       ,__A     )
									UpperCAmelCase__			 =				kwargs.pop('proxies'       ,__A     )
									UpperCAmelCase__			 =				kwargs.pop('local_files_only'       ,__A     )

									if os.path.isdir(__A     ):
													UpperCAmelCase__			 =				os.path.join(__A       ,__A     )
									elif os.path.isfile(__A     ) or is_remote_url(__A     ):
													UpperCAmelCase__			 =				pretrained_model_name_or_path
									else:
													UpperCAmelCase__			 =				hf_bucket_url(__A       ,filename=__A       ,use_cdn=__A     )

									try:
													# Load from URL or cache if already cached
													UpperCAmelCase__			 =				cached_path(
													    __A       ,cache_dir=__A       ,force_download=__A       ,proxies=__A       ,resume_download=__A       ,local_files_only=__A       ,)
													# Load config dict
													if resolved_config_file is None:
																	raise EnvironmentError

													UpperCAmelCase__			 =				Config.load_yaml(__A     )

									except EnvironmentError:
													UpperCAmelCase__			 =				'Can\'t load config for'
													raise EnvironmentError(__A     )

									if resolved_config_file == config_file:
													print('loading configuration file from path'     )
									else:
													print('loading configuration file cache'     )

									return Config.load_yaml(__A     ), kwargs






def     a_		(   lowerCamelCase			):
				UpperCAmelCase__			 =				torch.load('dump.pt'   ,     map_location=in_tensor.device			)
				UpperCAmelCase__			 =				in_tensor.numpy()
				UpperCAmelCase__			 =				out_tensor.numpy()[0]
				print(na.shape   ,     na[0, 0, :5]			)
				print(na.shape   ,     na[0, 0, :5]			)
				assert np.allclose(lowerCamelCase_   ,     lowerCamelCase_   ,     rtol=0.01   ,     atol=0.1			), (
				    f'''{sum([1 for x in np.isclose(lowerCamelCase_   ,     lowerCamelCase_   ,     rtol=0.01   ,     atol=0.1			).flatten() if x is False]			)/len(na.flatten()			)*1_0_0:.4f} %'''
				    " element-wise mismatch"
				)
				raise Exception('tensors are all good'			)

				# Hugging face functions below



def     a_		(   lowerCamelCase			):
				UpperCAmelCase__			 =				urlparse(lowerCamelCase_			)
				return parsed.scheme in ("http", "https")



def     a_		(   lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase=True			):
				UpperCAmelCase__			 =				CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
				UpperCAmelCase__			 =				'/' not in model_id
				if legacy_format:
								return f'''{endpoint}/{model_id}-{filename}'''
				else:
								return f'''{endpoint}/{model_id}/{filename}'''



def     a_		(   lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase=None   ,     lowerCamelCase=0   ,     lowerCamelCase=None   ,     ):
				UpperCAmelCase__			 =				'python/{}'.format(sys.version.split()[0]			)
				if _torch_available:
								ua += "; torch/{}".format(torch.__version__			)
				if isinstance(lowerCamelCase_   ,     lowerCamelCase_			):
								ua += "; " + "; ".join('{}/{}'.format(lowerCamelCase_   ,     lowerCamelCase_			) for k, v in user_agent.items()			)
				elif isinstance(lowerCamelCase_   ,     lowerCamelCase_			):
								ua += "; " + user_agent
				UpperCAmelCase__			 =				{'user-agent': ua}
				if resume_size > 0:
								UpperCAmelCase__			 =				'bytes=%d-' % (resume_size,)
				UpperCAmelCase__			 =				requests.get(lowerCamelCase_   ,     stream=lowerCamelCase_   ,     proxies=lowerCamelCase_   ,     headers=lowerCamelCase_			)
				if response.status_code == 4_1_6:  # Range not satisfiable
								return
				UpperCAmelCase__			 =				response.headers.get('Content-Length'			)
				UpperCAmelCase__			 =				resume_size + int(lowerCamelCase_			) if content_length is not None else None
				UpperCAmelCase__			 =				tqdm(
				    unit='B'   ,     unit_scale=lowerCamelCase_   ,     total=lowerCamelCase_   ,     initial=lowerCamelCase_   ,     desc='Downloading'   ,     )
				for chunk in response.iter_content(chunk_size=1_0_2_4			):
								if chunk:  # filter out keep-alive new chunks
												progress.update(len(lowerCamelCase_			)			)
												temp_file.write(lowerCamelCase_			)
				progress.close()



def     a_		(   lowerCamelCase   ,     lowerCamelCase=None   ,     lowerCamelCase=False   ,     lowerCamelCase=None   ,     lowerCamelCase=1_0   ,     lowerCamelCase=False   ,     lowerCamelCase=None   ,     lowerCamelCase=False   ,     ):
				if cache_dir is None:
								UpperCAmelCase__			 =				TRANSFORMERS_CACHE
				if isinstance(lowerCamelCase_   ,     lowerCamelCase_			):
								UpperCAmelCase__			 =				str(lowerCamelCase_			)

				os.makedirs(lowerCamelCase_   ,     exist_ok=lowerCamelCase_			)

				UpperCAmelCase__			 =				None
				if not local_files_only:
								try:
												UpperCAmelCase__			 =				requests.head(lowerCamelCase_   ,     allow_redirects=lowerCamelCase_   ,     proxies=lowerCamelCase_   ,     timeout=lowerCamelCase_			)
												if response.status_code == 2_0_0:
																UpperCAmelCase__			 =				response.headers.get('ETag'			)
								except (EnvironmentError, requests.exceptions.Timeout):
												# etag is already None
												pass

				UpperCAmelCase__			 =				url_to_filename(lowerCamelCase_   ,     lowerCamelCase_			)

				# get cache path to put the file
				UpperCAmelCase__			 =				os.path.join(lowerCamelCase_   ,     lowerCamelCase_			)

				# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
				# try to get the last downloaded one
				if etag is None:
								if os.path.exists(lowerCamelCase_			):
												return cache_path
								else:
												UpperCAmelCase__			 =				[
												    file
												    for file in fnmatch.filter(os.listdir(lowerCamelCase_			)   ,     filename + '.*'			)
												    if not file.endswith('.json'			) and not file.endswith('.lock'			)
												]
												if len(lowerCamelCase_			) > 0:
																return os.path.join(lowerCamelCase_   ,     matching_files[-1]			)
												else:
																# If files cannot be found and local_files_only=True,
																# the models might've been found if local_files_only=False
																# Notify the user about that
																if local_files_only:
																				raise ValueError(
																				    'Cannot find the requested files in the cached path and outgoing traffic has been'
																				    ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
																				    ' to False.'			)
																return None

    # From now on, etag is not None.
				if os.path.exists(lowerCamelCase_			) and not force_download:
								return cache_path

				# Prevent parallel downloads of the same file with a lock.
				UpperCAmelCase__			 =				cache_path + '.lock'
				with FileLock(lowerCamelCase_			):
								# If the download just completed while the lock was activated.
								if os.path.exists(lowerCamelCase_			) and not force_download:
												# Even if returning early like here, the lock will be released.
												return cache_path

								if resume_download:
												UpperCAmelCase__			 =				cache_path + '.incomplete'

												@contextmanager
												def _resumable_file_manager():
																with open(lowerCamelCase_   ,     'a+b'			) as f:
																				yield f

												UpperCAmelCase__			 =				_resumable_file_manager
												if os.path.exists(lowerCamelCase_			):
																UpperCAmelCase__			 =				os.stat(lowerCamelCase_			).st_size
												else:
																UpperCAmelCase__			 =				0
								else:
												UpperCAmelCase__			 =				partial(tempfile.NamedTemporaryFile   ,     dir=lowerCamelCase_   ,     delete=lowerCamelCase_			)
												UpperCAmelCase__			 =				0

								# Download to temporary file, then copy to cache dir once finished.
								# Otherwise you get corrupt cache entries if the download gets interrupted.
								with temp_file_manager() as temp_file:
												print(
												    '%s not found in cache or force_download set to True, downloading to %s'   ,     lowerCamelCase_   ,     temp_file.name   ,     )

												http_get(
												    lowerCamelCase_   ,     lowerCamelCase_   ,     proxies=lowerCamelCase_   ,     resume_size=lowerCamelCase_   ,     user_agent=lowerCamelCase_   ,     )

								os.replace(temp_file.name   ,     lowerCamelCase_			)

								UpperCAmelCase__			 =				{'url': url, 'etag': etag}
								UpperCAmelCase__			 =				cache_path + '.json'
								with open(lowerCamelCase_   ,     'w'			) as meta_file:
												json.dump(lowerCamelCase_   ,     lowerCamelCase_			)

				return cache_path



def     a_		(   lowerCamelCase   ,     lowerCamelCase=None			):
				UpperCAmelCase__			 =				url.encode('utf-8'			)
				UpperCAmelCase__			 =				shaaaa(lowerCamelCase_			)
				UpperCAmelCase__			 =				url_hash.hexdigest()

				if etag:
								UpperCAmelCase__			 =				etag.encode('utf-8'			)
								UpperCAmelCase__			 =				shaaaa(lowerCamelCase_			)
								filename += "." + etag_hash.hexdigest()

				if url.endswith('.h5'			):
								filename += ".h5"

				return filename



def     a_		(   lowerCamelCase   ,     lowerCamelCase=None   ,     lowerCamelCase=False   ,     lowerCamelCase=None   ,     lowerCamelCase=False   ,     lowerCamelCase=None   ,     lowerCamelCase=False   ,     lowerCamelCase=False   ,     lowerCamelCase=False   ,     ):
				if cache_dir is None:
								UpperCAmelCase__			 =				TRANSFORMERS_CACHE
				if isinstance(lowerCamelCase_   ,     lowerCamelCase_			):
								UpperCAmelCase__			 =				str(lowerCamelCase_			)
				if isinstance(lowerCamelCase_   ,     lowerCamelCase_			):
								UpperCAmelCase__			 =				str(lowerCamelCase_			)

				if is_remote_url(lowerCamelCase_			):
								# URL, so get it from the cache (downloading if necessary)
								UpperCAmelCase__			 =				get_from_cache(
								    lowerCamelCase_   ,     cache_dir=lowerCamelCase_   ,     force_download=lowerCamelCase_   ,     proxies=lowerCamelCase_   ,     resume_download=lowerCamelCase_   ,     user_agent=lowerCamelCase_   ,     local_files_only=lowerCamelCase_   ,     )
				elif os.path.exists(lowerCamelCase_			):
								# File, and it exists.
								UpperCAmelCase__			 =				url_or_filename
				elif urlparse(lowerCamelCase_			).scheme == "":
								# File, but it doesn't exist.
								raise EnvironmentError('file {} not found'.format(lowerCamelCase_			)			)
				else:
								# Something unknown
								raise ValueError('unable to parse {} as a URL or as a local path'.format(lowerCamelCase_			)			)

				if extract_compressed_file:
								if not is_zipfile(lowerCamelCase_			) and not tarfile.is_tarfile(lowerCamelCase_			):
												return output_path

								# Path where we extract compressed archives
								# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
								UpperCAmelCase__ ,      UpperCAmelCase__			 =				os.path.split(lowerCamelCase_			)
								UpperCAmelCase__			 =				output_file.replace('.'   ,     '-'			) + '-extracted'
								UpperCAmelCase__			 =				os.path.join(lowerCamelCase_   ,     lowerCamelCase_			)

								if os.path.isdir(lowerCamelCase_			) and os.listdir(lowerCamelCase_			) and not force_extract:
												return output_path_extracted

								# Prevent parallel extractions
								UpperCAmelCase__			 =				output_path + '.lock'
								with FileLock(lowerCamelCase_			):
												shutil.rmtree(lowerCamelCase_   ,     ignore_errors=lowerCamelCase_			)
												os.makedirs(lowerCamelCase_			)
												if is_zipfile(lowerCamelCase_			):
																with ZipFile(lowerCamelCase_   ,     'r'			) as zip_file:
																				zip_file.extractall(lowerCamelCase_			)
																				zip_file.close()
												elif tarfile.is_tarfile(lowerCamelCase_			):
																UpperCAmelCase__			 =				tarfile.open(lowerCamelCase_			)
																tar_file.extractall(lowerCamelCase_			)
																tar_file.close()
												else:
																raise EnvironmentError('Archive format of {} could not be identified'.format(lowerCamelCase_			)			)

								return output_path_extracted

				return output_path



def     a_		(   lowerCamelCase   ,     lowerCamelCase=","			):
				assert isinstance(lowerCamelCase_   ,     lowerCamelCase_			)
				if os.path.isfile(lowerCamelCase_			):
								with open(lowerCamelCase_			) as f:
												UpperCAmelCase__			 =				eval(f.read()			)
				else:
								UpperCAmelCase__			 =				requests.get(lowerCamelCase_			)
								try:
												UpperCAmelCase__			 =				requests.json()
								except Exception:
												UpperCAmelCase__			 =				req.content.decode()
												assert data is not None, "could not connect"
												try:
																UpperCAmelCase__			 =				eval(lowerCamelCase_			)
												except Exception:
																UpperCAmelCase__			 =				data.split('\n'			)
								req.close()
				return data



def     a_		(   lowerCamelCase			):
				UpperCAmelCase__			 =				requests.get(lowerCamelCase_			)
				UpperCAmelCase__			 =				np.array(Image.open(BytesIO(response.content			)			)			)
				return img



def     a_		(   lowerCamelCase			):
				UpperCAmelCase__			 =				url.split('/'			)[-1]
				if fn not in os.listdir(os.getcwd()			):
								wget.download(lowerCamelCase_			)
				with open(lowerCamelCase_   ,     'rb'			) as stream:
								UpperCAmelCase__			 =				pkl.load(lowerCamelCase_			)
				UpperCAmelCase__			 =				weights.pop('model'			)
				UpperCAmelCase__			 =				{}
				for k, v in model.items():
								UpperCAmelCase__			 =				torch.from_numpy(lowerCamelCase_			)
								if "running_var" in k:
												UpperCAmelCase__			 =				torch.tensor([0]			)
												UpperCAmelCase__			 =				k.replace('running_var'   ,     'num_batches_tracked'			)
												UpperCAmelCase__			 =				zero
				return new



def     a_		(   ):
				print(f'''{os.path.abspath(os.path.join(lowerCamelCase_   ,     os.pardir			)			)}/demo.ipynb'''			)



def     a_		(   lowerCamelCase   ,     lowerCamelCase="RGB"			):
				assert isinstance(lowerCamelCase_   ,     lowerCamelCase_			)
				if os.path.isfile(lowerCamelCase_			):
								UpperCAmelCase__			 =				cva.imread(lowerCamelCase_			)
				else:
								UpperCAmelCase__			 =				get_image_from_url(lowerCamelCase_			)
								assert img is not None, f'''could not connect to: {im}'''
				UpperCAmelCase__			 =				cva.cvtColor(lowerCamelCase_   ,     cva.COLOR_BGR2RGB			)
				if input_format == "RGB":
								UpperCAmelCase__			 =				img[:, :, ::-1]
				return img







def     a_		(   lowerCamelCase   ,     lowerCamelCase=1			):
				return (images[i : i + batch] for i in range(0   ,     len(lowerCamelCase_			)   ,     lowerCamelCase_			))











"""simple docstring"""







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

from transformers import BigBirdTokenizerFast


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





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=0			,  lowerCamelCase_=None):
					return [" ".join(x.split(''' ''')[begin:end]) for x in answers if len(x.split(''' ''')) > 1]





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=False):
					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__ 							=	(
										    given_answers + get_sub_answers(lowerCamelCase_			,  begin=1) + get_sub_answers(lowerCamelCase_			,  end=-1)
										)
					a__ 							=	[]
					for answer in given_answers:
										a__ 							=	answer.replace('''_'''			,  ''' ''').lower()
										a__ 							=	''''''.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 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_			,  lowerCamelCase_=1			,  lowerCamelCase_=100):
					a__							,a__ 							=	jax.lax.top_k(lowerCamelCase_			,  lowerCamelCase_)
					a__							,a__ 							=	jax.lax.top_k(lowerCamelCase_			,  lowerCamelCase_)

					a__ 							=	best_end_idx[:, None] - best_start_idx[None, :]
					a__ 							=	jnp.logical_or(widths < 0			,  widths > max_size)
					a__ 							=	(best_end_scores[:, None] + best_start_scores[None, :]) - (1E8 * mask)
					a__ 							=	jnp.argmax(lowerCamelCase_).item()

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





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	sample['''question''']['''text''']
					a__ 							=	sample['''document''']['''tokens''']['''token''']
					a__ 							=	sample['''document''']['''tokens''']['''is_html''']
					a__ 							=	sample['''annotations''']['''long_answer''']
					a__ 							=	sample['''annotations''']['''short_answers''']

					a__ 							=	''' '''.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__ 							=	[]
					for s in short_answers:
										short_targets.extend(s['''text'''])
					a__ 							=	list(set(lowerCamelCase_))

					a__ 							=	[]
					for s in long_answers:
										if s["start_token"] == -1:
															continue
										a__ 							=	context[s['''start_token'''] : s['''end_token''']]
										a__ 							=	is_html[s['''start_token'''] : s['''end_token''']]
										a__ 							=	''' '''.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__ 							=	'''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 							SCREAMING_SNAKE_CASE							(   ):
					a__ 							=	load_from_disk('''natural-questions-validation''')
					a__ 							=	dataset.map(lowerCamelCase_).remove_columns(['''annotations''', '''document''', '''id'''])
					print(lowerCamelCase_)

					a__ 							=	dataset.filter(lambda lowerCamelCase_: (len(x['''question''']) + len(x['''context'''])) < 4 * 4096)
					a__ 							=	short_validation_dataset.filter(lambda lowerCamelCase_: x["category"] != "null")
					short_validation_dataset

					a__ 							=	'''vasudevgupta/flax-bigbird-natural-questions'''
					a__ 							=	FlaxBigBirdForNaturalQuestions.from_pretrained(lowerCamelCase_)
					a__ 							=	BigBirdTokenizerFast.from_pretrained(lowerCamelCase_)

					@jax.jit
					def forward(*lowerCamelCase_			,  **lowerCamelCase_):
										a__							,a__							,a__ 							=	model(*lowerCamelCase_			,  **lowerCamelCase_)
										return start_logits, end_logits, jnp.argmax(lowerCamelCase_			,  axis=-1)

					def evaluate(lowerCamelCase_):
										# encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
										a__ 							=	tokenizer(
										    example['''question''']			,  example['''context''']			,  return_tensors='''np'''			,  max_length=4096			,  padding='''max_length'''			,  truncation=lowerCamelCase_			,  )

										a__							,a__							,a__ 							=	forward(**lowerCamelCase_)

										a__ 							=	CATEGORY_MAPPING[category.item()]

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

										if predicted_category in ["yes", "no", "null"]:
															a__ 							=	[predicted_category]
															a__ 							=	example['''output'''] == example['''targets''']
															a__ 							=	predicted_category != '''null'''
															return example

										a__ 							=	38 if predicted_category == '''short''' else 1024
										a__							,a__ 							=	get_best_valid_start_end_idx(
										    start_scores[0]			,  end_scores[0]			,  top_k=8			,  max_size=lowerCamelCase_)

										a__ 							=	inputs['''input_ids'''][0].tolist()
										a__ 							=	[tokenizer.decode(input_ids[start_score : end_score + 1])]

										a__ 							=	expand_to_aliases(example['''targets''']			,  make_sub_answers=lowerCamelCase_)
										a__ 							=	expand_to_aliases(example['''output'''])

										# some preprocessing to both prediction and answer
										a__ 							=	{''''''.join(a.split()) for a in answers}
										a__ 							=	{''''''.join(p.split()) for p in predictions}
										a__ 							=	{s for s in predictions if s not in ['''``''', '''\'\'''', '''`''', '''\'''']}

										# if there is a common element, it's a exact match
										a__ 							=	len(list(answers & predictions)) > 0
										a__ 							=	predicted_category != '''null''' and len(lowerCamelCase_) > 0

										return example

					a__ 							=	short_validation_dataset.map(lowerCamelCase_)

					a__ 							=	len(lowerCamelCase_)
					a__ 							=	len(short_validation_dataset.filter(lambda lowerCamelCase_: x["match"] == 1))
					print('''EM score:'''			,  (matched / total) * 100			,  '''%''')


if __name__ == "__main__":
	main()


