
'''simple docstring'''


from collections import OrderedDict
from typing import Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging


__lowercase							:   List[Any]					=     logging.get_logger(__name__)

__lowercase							:   Optional[int]					=     {
    '''deepmind/language-perceiver''': '''https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json''',
    # See all Perceiver models at https://huggingface.co/models?filter=perceiver
}

class 	__lowercase				(  _lowercase    ):
			lowerCamelCase			:		str	      =			"perceiver"

			def __init__(self			,   A=2_5_6			,   A=1_2_8_0			,   A=7_6_8			,   A=1			,   A=2_6			,   A=8			,   A=8			,   A=None			,   A=None			,   A="kv"			,   A=1			,   A=1			,   A="gelu"			,   A=0.1			,   A=0.02			,   A=1E-12			,   A=True			,   A=2_6_2			,   A=2_0_4_8			,   A=5_6			,   A=[3_6_8, 4_9_6]			,   A=1_6			,   A=1_9_2_0			,   A=1_6			,   A=[1, 1_6, 2_2_4, 2_2_4]			,   **A			,   ):
								super().__init__(**A      )

								lowerCamelCase_					:      Dict     =		num_latents
								lowerCamelCase_					:      Dict     =		d_latents
								lowerCamelCase_					:      Optional[Any]     =		d_model
								lowerCamelCase_					:      List[str]     =		num_blocks
								lowerCamelCase_					:      Dict     =		num_self_attends_per_block
								lowerCamelCase_					:      str     =		num_self_attention_heads
								lowerCamelCase_					:      Optional[Any]     =		num_cross_attention_heads
								lowerCamelCase_					:      Tuple     =		qk_channels
								lowerCamelCase_					:      Optional[int]     =		v_channels
								lowerCamelCase_					:      Optional[int]     =		cross_attention_shape_for_attention
								lowerCamelCase_					:      Any     =		self_attention_widening_factor
								lowerCamelCase_					:      Union[str, Any]     =		cross_attention_widening_factor
								lowerCamelCase_					:      Union[str, Any]     =		hidden_act
								lowerCamelCase_					:      str     =		attention_probs_dropout_prob
								lowerCamelCase_					:      List[str]     =		initializer_range
								lowerCamelCase_					:      Union[str, Any]     =		layer_norm_eps
								lowerCamelCase_					:      List[Any]     =		use_query_residual
								# masked language modeling attributes
								lowerCamelCase_					:      Any     =		vocab_size
								lowerCamelCase_					:      Dict     =		max_position_embeddings
								# image classification attributes
								lowerCamelCase_					:      int     =		image_size
								# flow attributes
								lowerCamelCase_					:      str     =		train_size
								# multimodal autoencoding attributes
								lowerCamelCase_					:      List[Any]     =		num_frames
								lowerCamelCase_					:      Optional[int]     =		audio_samples_per_frame
								lowerCamelCase_					:      str     =		samples_per_patch
								lowerCamelCase_					:      Dict     =		output_shape

class 	__lowercase				(  _lowercase    ):

			@property
			def        UpperCAmelCase__ (self      ):
								if self.task == "multiple-choice":
													lowerCamelCase_					:      Optional[int]     =		{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
								else:
													lowerCamelCase_					:      int     =		{0: '''batch''', 1: '''sequence'''}
								return OrderedDict(
								    [
								        ('''inputs''', dynamic_axis),
								        ('''attention_mask''', dynamic_axis),
								    ]      )

			@property
			def        UpperCAmelCase__ (self      ):
								return 1E-4






			def        UpperCAmelCase__ (self			,   A			,   A = -1			,   A = -1			,   A = -1			,   A = False			,   A = None			,   A = 3			,   A = 4_0			,   A = 4_0			,   ):
								# copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified

								if isinstance(A			,   A      ):
													# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
													lowerCamelCase_					:      Optional[Any]     =		compute_effective_axis_dimension(
													    A			,   fixed_dimension=OnnxConfig.default_fixed_batch			,   num_token_to_add=0      )
													# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
													lowerCamelCase_					:      List[str]     =		preprocessor.num_special_tokens_to_add(A      )
													lowerCamelCase_					:      Dict     =		compute_effective_axis_dimension(
													    A			,   fixed_dimension=OnnxConfig.default_fixed_sequence			,   num_token_to_add=A      )
													# Generate dummy inputs according to compute batch and sequence
													lowerCamelCase_					:      Dict     =		[''' '''.join(['''a''']      ) * seq_length] * batch_size
													lowerCamelCase_					:      Dict     =		dict(preprocessor(A			,   return_tensors=A      )      )
													lowerCamelCase_					:      Optional[int]     =		inputs.pop('''input_ids'''      )
													return inputs
								elif isinstance(A			,   A      ) and preprocessor.model_input_names[0] == "pixel_values":
													# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
													lowerCamelCase_					:      Tuple     =		compute_effective_axis_dimension(A			,   fixed_dimension=OnnxConfig.default_fixed_batch      )
													lowerCamelCase_					:      Tuple     =		self._generate_dummy_images(A			,   A			,   A			,   A      )
													lowerCamelCase_					:      List[Any]     =		dict(preprocessor(images=A			,   return_tensors=A      )      )
													lowerCamelCase_					:      str     =		inputs.pop('''pixel_values'''      )
													return inputs
								else:
													raise ValueError(
													    '''Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.'''      )




'''simple docstring'''


import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def lowercase_	(   _lowercase			,       _lowercase=False				)     ->							int:
					'''simple docstring'''

					try:
										lowerCamelCase_					:      Union[str, Any]     =		os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										lowerCamelCase_					:      Union[str, Any]     =		default
					else:
										# KEY is set, convert it to True or False.
										try:
															lowerCamelCase_					:      List[str]     =		strtobool(_lowercase				)
										except ValueError:
															# More values are supported, but let's keep the message simple.
															raise ValueError(F"""If set, {key} must be yes or no."""				)
					return _value


__lowercase							:   Union[str, Any]					=     parse_flag_from_env('''RUN_SLOW''', default=False)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skip('''Test was skipped'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Optional[Any]:
					'''simple docstring'''

					return unittest.skipUnless(_run_slow_tests			,       '''test is slow'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(not torch.cuda.is_available()			,       '''test requires only a CPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.is_available()			,       '''test requires a GPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(is_xpu_available()			,       '''test requires a XPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(is_mps_available()			,       '''test requires a `mps` backend support in `torch`'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(
					    is_transformers_available() and is_datasets_available()			,       '''test requires the Hugging Face suite'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(is_bnb_available()			,       '''test requires the bitsandbytes library'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_tpu_available()			,       '''test requires TPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() == 1			,       '''test requires a GPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() == 1			,       '''test requires a XPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() > 1			,       '''test requires multiple GPUs'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() > 1			,       '''test requires multiple XPUs'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(is_safetensors_available()			,       '''test requires safetensors'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							int:
					'''simple docstring'''

					return unittest.skipUnless(is_deepspeed_available()			,       '''test requires DeepSpeed'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_torch_version('''>='''			,       '''1.12.0'''				)			,       '''test requires torch version >= 1.12.0'''				)(_lowercase				)




def lowercase_	(   _lowercase=None			,       _lowercase=None				)     ->							Any:
					'''simple docstring'''

					if test_case is None:
										return partial(_lowercase			,       version=_lowercase				)
					return unittest.skipUnless(is_torch_version('''>='''			,       _lowercase				)			,       F"""test requires torch version >= {version}"""				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(is_tensorboard_available()			,       '''test requires Tensorboard'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_wandb_available()			,       '''test requires wandb'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							int:
					'''simple docstring'''

					return unittest.skipUnless(is_comet_ml_available()			,       '''test requires comet_ml'''				)(_lowercase				)


__lowercase							:   str					=     (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def lowercase_	(   _lowercase				)     ->							List[Any]:
					'''simple docstring'''

					return unittest.skipUnless(
					    _atleast_one_tracker_available			,       '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''			,       )(_lowercase				)

class 	__lowercase				(  unittest.TestCase    ):
			lowerCamelCase			:		Optional[Any]	      =			True

			@classmethod
			def        UpperCAmelCase__ (cls      ):
								lowerCamelCase_					:      Optional[Any]     =		tempfile.mkdtemp()

			@classmethod
			def        UpperCAmelCase__ (cls      ):
								if os.path.exists(cls.tmpdir      ):
													shutil.rmtree(cls.tmpdir      )






			def        UpperCAmelCase__ (self      ):
								if self.clear_on_setup:
													for path in Path(self.tmpdir      ).glob('''**/*'''      ):
																		if path.is_file():
																							path.unlink()
																		elif path.is_dir():
																							shutil.rmtree(A      )

class 	__lowercase				(  unittest.TestCase    ):

			def        UpperCAmelCase__ (self      ):
								super().tearDown()
								# Reset the state of the AcceleratorState singleton.
								AcceleratorState._reset_state()
								PartialState._reset_state()

class 	__lowercase				(  unittest.TestCase    ):

			def        UpperCAmelCase__ (self			,   A      ):
								lowerCamelCase_					:      List[str]     =		mocks if isinstance(A			,   (tuple, list)      ) else [mocks]
								for m in self.mocks:
													m.start()
													self.addCleanup(m.stop      )




def lowercase_	(   _lowercase				)     ->							Optional[int]:
					'''simple docstring'''

					lowerCamelCase_					:      Tuple     =		AcceleratorState()
					lowerCamelCase_					:      Optional[Any]     =		tensor[None].clone().to(state.device				)
					lowerCamelCase_					:      Dict     =		gather(_lowercase				).cpu()
					lowerCamelCase_					:      List[str]     =		tensor[0].cpu()
					for i in range(tensors.shape[0]				):
										if not torch.equal(tensors[i]			,       _lowercase				):
															return False
					return True

class 	__lowercase				:

			def __init__(self			,   A			,   A			,   A      ):
								lowerCamelCase_					:      List[Any]     =		returncode
								lowerCamelCase_					:      Optional[int]     =		stdout
								lowerCamelCase_					:      List[str]     =		stderr




async def lowercase_	(   _lowercase			,       _lowercase				)     ->							Tuple:
					'''simple docstring'''

					while True:
										lowerCamelCase_					:      Any     =		await stream.readline()
										if line:
															callback(_lowercase				)
										else:
															break




async def lowercase_	(   _lowercase			,       _lowercase=None			,       _lowercase=None			,       _lowercase=None			,       _lowercase=False			,       _lowercase=False				)     ->							_RunOutput:
					'''simple docstring'''

					if echo:
										print('''\nRunning: '''			,       ''' '''.join(_lowercase				)				)

					lowerCamelCase_					:      Any     =		await asyncio.create_subprocess_exec(
					    cmd[0]			,       *cmd[1:]			,       stdin=_lowercase			,       stdout=asyncio.subprocess.PIPE			,       stderr=asyncio.subprocess.PIPE			,       env=_lowercase			,       )

					# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
					# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
					#
					# If it starts hanging, will need to switch to the following code. The problem is that no data
					# will be seen until it's done and if it hangs for example there will be no debug info.
					# out, err = await p.communicate()
					# return _RunOutput(p.returncode, out, err)

					lowerCamelCase_					:      List[Any]     =		[]
					lowerCamelCase_					:      Optional[int]     =		[]

					def tee(_lowercase			,       _lowercase			,       _lowercase			,       _lowercase=""				):
										lowerCamelCase_					:      Union[str, Any]     =		line.decode('''utf-8'''				).rstrip()
										sink.append(_lowercase				)
										if not quiet:
															print(_lowercase			,       _lowercase			,       file=_lowercase				)

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        asyncio.create_task(_read_stream(p.stdout			,       lambda _lowercase				: tee(_lowercase			,       _lowercase			,       sys.stdout			,       label='''stdout:'''				)				)				),
					        asyncio.create_task(_read_stream(p.stderr			,       lambda _lowercase				: tee(_lowercase			,       _lowercase			,       sys.stderr			,       label='''stderr:'''				)				)				),
					    ]			,       timeout=_lowercase			,       )
					return _RunOutput(await p.wait()			,       _lowercase			,       _lowercase				)




def lowercase_	(   _lowercase			,       _lowercase=None			,       _lowercase=None			,       _lowercase=180			,       _lowercase=False			,       _lowercase=True				)     ->							_RunOutput:
					'''simple docstring'''

					lowerCamelCase_					:      Any     =		asyncio.get_event_loop()
					lowerCamelCase_					:      List[str]     =		loop.run_until_complete(
					    _stream_subprocess(_lowercase			,       env=_lowercase			,       stdin=_lowercase			,       timeout=_lowercase			,       quiet=_lowercase			,       echo=_lowercase				)				)

					lowerCamelCase_					:      List[Any]     =		''' '''.join(_lowercase				)
					if result.returncode > 0:
										lowerCamelCase_					:      Optional[int]     =		'''\n'''.join(result.stderr				)
										raise RuntimeError(
										    F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
										    F"""The combined stderr from workers follows:\n{stderr}"""				)

					return result

class 	__lowercase				(  _lowercase    ):
			pass




def lowercase_	(   _lowercase			,       _lowercase=False				)     ->							Dict:
					'''simple docstring'''

					try:
										lowerCamelCase_					:      List[str]     =		subprocess.check_output(_lowercase			,       stderr=subprocess.STDOUT				)
										if return_stdout:
															if hasattr(_lowercase			,       '''decode'''				):
																				lowerCamelCase_					:      str     =		output.decode('''utf-8'''				)
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    F"""Command `{" ".join(_lowercase				)}` failed with the following error:\n\n{e.output.decode()}"""				) from e


