"""simple docstring"""
import unittest

from transformers import PegasusConfig, PegasusTokenizer, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
					import os

					# The slow tests are often failing with OOM error on GPU
					# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
					# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
					SCREAMING_SNAKE_CASE__   =					"platform"
					import jax
					import jax.numpy as jnp
					import numpy as np

					from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel



@require_flax
class 					lowerCAmelCase_      :



				"""simple docstring"""
				_lowerCAmelCase       :      Tuple     					=  PegasusConfig
				_lowerCAmelCase       :      Optional[Any]     					=  {}
				_lowerCAmelCase       :      int     					=  """gelu"""

				def __init__(			self						,      lowerCAmelCase						,      lowerCAmelCase=13						,      lowerCAmelCase=7						,      lowerCAmelCase=True						,      lowerCAmelCase=False						,      lowerCAmelCase=99						,      lowerCAmelCase=32						,      lowerCAmelCase=5						,      lowerCAmelCase=4						,      lowerCAmelCase=37						,      lowerCAmelCase=0.1						,      lowerCAmelCase=0.1						,      lowerCAmelCase=20						,      lowerCAmelCase=2						,      lowerCAmelCase=1						,      lowerCAmelCase=0						,      ):






										"""simple docstring"""

										snake_case        =     parent
										snake_case        =     batch_size
										snake_case        =     seq_length
										snake_case        =     is_training
										snake_case        =     use_labels
										snake_case        =     vocab_size
										snake_case        =     hidden_size
										snake_case        =     num_hidden_layers
										snake_case        =     num_attention_heads
										snake_case        =     intermediate_size

										snake_case        =     hidden_dropout_prob
										snake_case        =     attention_probs_dropout_prob
										snake_case        =     max_position_embeddings
										snake_case        =     eos_token_id
										snake_case        =     pad_token_id
										snake_case        =     bos_token_id

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case        =     ids_tensor([self.batch_size, self.seq_length - 1]						,      self.vocab_size      ).clip(3						,      self.vocab_size      )
										snake_case        =     np.expand_dims(np.array([self.eos_token_id] * self.batch_size      )						,      1      )
										snake_case        =     np.concatenate([input_ids, eos_tensor]						,      axis=1      )

										snake_case        =     ids_tensor([self.batch_size, self.seq_length]						,      self.vocab_size      )

										snake_case        =     self.config_cls(
										    vocab_size=self.vocab_size						,      d_model=self.hidden_size						,      encoder_layers=self.num_hidden_layers						,      decoder_layers=self.num_hidden_layers						,      encoder_attention_heads=self.num_attention_heads						,      decoder_attention_heads=self.num_attention_heads						,      encoder_ffn_dim=self.intermediate_size						,      decoder_ffn_dim=self.intermediate_size						,      dropout=self.hidden_dropout_prob						,      attention_dropout=self.attention_probs_dropout_prob						,      max_position_embeddings=self.max_position_embeddings						,      eos_token_ids=[2]						,      bos_token_id=self.bos_token_id						,      pad_token_id=self.pad_token_id						,      decoder_start_token_id=self.pad_token_id						,      **self.config_updates						,      )
										snake_case        =     prepare_pegasus_inputs_dict(lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      )
										return config, inputs_dict

				def 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     20
										snake_case        =     model_class_name(lowerCAmelCase      )

										snake_case        =     model.encode(inputs_dict['input_ids']      )

										snake_case   ,snake_case        =     (
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

										snake_case        =     model.init_cache(decoder_input_ids.shape[0]						,      lowerCAmelCase						,      lowerCAmelCase      )
										snake_case        =     jnp.ones((decoder_input_ids.shape[0], max_decoder_length)						,      dtype='i4'      )

										snake_case        =     jnp.broadcast_to(
										    jnp.arange(decoder_input_ids.shape[-1] - 1      )[None, :]						,      (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,      )
										snake_case        =     model.decode(
										    decoder_input_ids[:, :-1]						,      lowerCAmelCase						,      decoder_attention_mask=lowerCAmelCase						,      past_key_values=lowerCAmelCase						,      decoder_position_ids=lowerCAmelCase						,      )

										snake_case        =     jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,      dtype='i4'      )
										snake_case        =     model.decode(
										    decoder_input_ids[:, -1:]						,      lowerCAmelCase						,      decoder_attention_mask=lowerCAmelCase						,      past_key_values=outputs_cache.past_key_values						,      decoder_position_ids=lowerCAmelCase						,      )

										snake_case        =     model.decode(lowerCAmelCase						,      lowerCAmelCase      )

										snake_case        =     np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])      )      )
										self.parent.assertTrue(diff < 1E-3						,      msg=F"""Max diff is {diff}"""      )

				def 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     20
										snake_case        =     model_class_name(lowerCAmelCase      )

										snake_case        =     model.encode(inputs_dict['input_ids']      )

										snake_case   ,snake_case        =     (
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

										snake_case        =     jnp.concatenate(
										    [
										        decoder_attention_mask,
										        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])      ),
										    ]						,      axis=-1						,      )

										snake_case        =     model.init_cache(decoder_input_ids.shape[0]						,      lowerCAmelCase						,      lowerCAmelCase      )
										snake_case        =     jnp.broadcast_to(
										    jnp.arange(decoder_input_ids.shape[-1] - 1      )[None, :]						,      (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,      )

										snake_case        =     model.decode(
										    decoder_input_ids[:, :-1]						,      lowerCAmelCase						,      decoder_attention_mask=lowerCAmelCase						,      past_key_values=lowerCAmelCase						,      decoder_position_ids=lowerCAmelCase						,      )
										snake_case        =     jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,      dtype='i4'      )
										snake_case        =     model.decode(
										    decoder_input_ids[:, -1:]						,      lowerCAmelCase						,      past_key_values=outputs_cache.past_key_values						,      decoder_attention_mask=lowerCAmelCase						,      decoder_position_ids=lowerCAmelCase						,      )

										snake_case        =     model.decode(lowerCAmelCase						,      lowerCAmelCase						,      decoder_attention_mask=lowerCAmelCase      )

										snake_case        =     np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])      )      )
										self.parent.assertTrue(diff < 1E-3						,      msg=F"""Max diff is {diff}"""      )





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[str]	,     _UpperCamelCase    :			Optional[Any]	,     _UpperCamelCase    :			int	,     _UpperCamelCase    :			str=None	,     _UpperCamelCase    :			Dict=None	,     )   ->			Optional[Any]:





						"""simple docstring"""






						if attention_mask is None:
												snake_case        =     np.not_equal(_UpperCamelCase	,     config.pad_token_id   ).astype(np.inta   )
						if decoder_attention_mask is None:
												snake_case        =     np.concatenate(
												    [
												        np.ones(decoder_input_ids[:, :1].shape	,     dtype=np.inta   ),
												        np.not_equal(decoder_input_ids[:, 1:]	,     config.pad_token_id   ).astype(np.inta   ),
												    ]	,     axis=-1	,     )
						return {
						    "input_ids": input_ids,
						    "decoder_input_ids": decoder_input_ids,
						    "attention_mask": attention_mask,
						    "decoder_attention_mask": decoder_attention_mask,
						}



@require_flax
class 					lowerCAmelCase_      (     lowerCAmelCase       ,      unittest.TestCase   ):



				"""simple docstring"""
				_lowerCAmelCase       :      Dict     					=  (
				    (
				        FlaxPegasusForConditionalGeneration,
				        FlaxPegasusModel,
				    )
				    if is_flax_available()
				    else ()
				)
				_lowerCAmelCase       :      Any     					=  (FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
				_lowerCAmelCase       :      Optional[Any]     					=  True
				_lowerCAmelCase       :      int     					=  False
				_lowerCAmelCase       :      Tuple     					=  False
				_lowerCAmelCase       :      Dict     					=  False

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case        =     FlaxPegasusModelTester(self      )
										snake_case        =     ConfigTester(self						,      config_class=lowerCAmelCase      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

										self.config_tester.run_common_tests()

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case   ,snake_case        =     self.model_tester.prepare_config_and_inputs_for_common()
										for model_class in self.all_model_classes:
																self.model_tester.check_use_cache_forward(lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case   ,snake_case        =     self.model_tester.prepare_config_and_inputs_for_common()
										for model_class in self.all_model_classes:
																self.model_tester.check_use_cache_forward_with_attn_mask(lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case   ,snake_case        =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																with self.subTest(model_class.__name__      ):
																						snake_case        =     self._prepare_for_class(lowerCAmelCase						,      lowerCAmelCase      )
																						snake_case        =     model_class(lowerCAmelCase      )

																						@jax.jit
																						def encode_jitted(lowerCAmelCase						,      lowerCAmelCase=None						,      **lowerCAmelCase      ):
																												return model.encode(input_ids=lowerCAmelCase						,      attention_mask=lowerCAmelCase      )

																						with self.subTest('JIT Enabled'      ):
																												snake_case        =     encode_jitted(**lowerCAmelCase      ).to_tuple()

																						with self.subTest('JIT Disabled'      ):
																												with jax.disable_jit():
																																		snake_case        =     encode_jitted(**lowerCAmelCase      ).to_tuple()

																						self.assertEqual(len(lowerCAmelCase      )						,      len(lowerCAmelCase      )      )
																						for jitted_output, output in zip(lowerCAmelCase						,      lowerCAmelCase      ):
																												self.assertEqual(jitted_output.shape						,      output.shape      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case   ,snake_case        =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																with self.subTest(model_class.__name__      ):
																						snake_case        =     model_class(lowerCAmelCase      )
																						snake_case        =     model.encode(inputs_dict['input_ids']						,      inputs_dict['attention_mask']      )

																						snake_case        =     {
																						    'decoder_input_ids': inputs_dict['decoder_input_ids'],
																						    'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
																						    'encoder_outputs': encoder_outputs,
																						}

																						@jax.jit
																						def decode_jitted(lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      ):
																												return model.decode(
																												    decoder_input_ids=lowerCAmelCase						,      decoder_attention_mask=lowerCAmelCase						,      encoder_outputs=lowerCAmelCase						,      )

																						with self.subTest('JIT Enabled'      ):
																												snake_case        =     decode_jitted(**lowerCAmelCase      ).to_tuple()

																						with self.subTest('JIT Disabled'      ):
																												with jax.disable_jit():
																																		snake_case        =     decode_jitted(**lowerCAmelCase      ).to_tuple()

																						self.assertEqual(len(lowerCAmelCase      )						,      len(lowerCAmelCase      )      )
																						for jitted_output, output in zip(lowerCAmelCase						,      lowerCAmelCase      ):
																												self.assertEqual(jitted_output.shape						,      output.shape      )

				@slow
				def 						snake_case	(			self      ):






										"""simple docstring"""

										for model_class_name in self.all_model_classes:
																snake_case        =     model_class_name.from_pretrained('google/pegasus-large'						,      from_pt=lowerCAmelCase      )
																snake_case        =     np.ones((1, 1)      )
																snake_case        =     model(lowerCAmelCase      )
																self.assertIsNotNone(lowerCAmelCase      )

				@slow
				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case        =     FlaxPegasusForConditionalGeneration.from_pretrained('google/pegasus-xsum'      )
										snake_case        =     PegasusTokenizer.from_pretrained('google/pegasus-xsum'      )

										snake_case        =     [
										    ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
										    ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
										]

										snake_case        =     [
										    'California\'s largest electricity provider has turned off power to hundreds of thousands of customers.',
										    'Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.',
										]

										snake_case        =     tokenizer(lowerCAmelCase						,      return_tensors='np'						,      truncation=lowerCAmelCase						,      max_length=5_12						,      padding=lowerCAmelCase      )
										snake_case        =     model.generate(**lowerCAmelCase						,      num_beams=2      ).sequences
										snake_case        =     tokenizer.batch_decode(lowerCAmelCase						,      skip_special_tokens=lowerCAmelCase      )
										assert tgt_text == decoded



"""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 				lowerCAmelCase__      (     _UpperCamelCase    :			Tuple	,     _UpperCamelCase    :			Optional[int]=False   )   ->			Any:





						"""simple docstring"""






						try:
												snake_case        =     os.environ[key]
						except KeyError:
												# KEY isn't set, default to `default`.
												snake_case        =     default
						else:
												# KEY is set, convert it to True or False.
												try:
																		snake_case        =     strtobool(_UpperCamelCase   )
												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


SCREAMING_SNAKE_CASE__   =					parse_flag_from_env("RUN_SLOW", default=False)





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[Any]   )   ->			str:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[Any]   )   ->			List[str]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[Any]   )   ->			int:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Tuple   )   ->			Tuple:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			Optional[int]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			Any:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Tuple   )   ->			str:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[str]   )   ->			Dict:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[str]   )   ->			List[Any]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			int:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			str   )   ->			List[Any]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Optional[Any]   )   ->			List[Any]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			str   )   ->			List[str]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			str   )   ->			str:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			List[str]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			int   )   ->			List[Any]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict=None	,     _UpperCamelCase    :			Dict=None   )   ->			int:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Optional[int]   )   ->			List[str]:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			int   )   ->			int:





						"""simple docstring"""






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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			int   )   ->			Any:





						"""simple docstring"""






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


SCREAMING_SNAKE_CASE__   =					(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def 				lowerCAmelCase__      (     _UpperCamelCase    :			str   )   ->			List[str]:





						"""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'	,     )(_UpperCamelCase   )



class 					lowerCAmelCase_      (     unittest.TestCase   ):



				"""simple docstring"""
				_lowerCAmelCase       :      Union[str, Any]     					=  True

				@classmethod
				def 						snake_case	(			cls      ):






										"""simple docstring"""

										snake_case        =     tempfile.mkdtemp()

				@classmethod
				def 						snake_case	(			cls      ):






										"""simple docstring"""

										if os.path.exists(cls.tmpdir      ):
																shutil.rmtree(cls.tmpdir      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

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





class 					lowerCAmelCase_      (     unittest.TestCase   ):



				"""simple docstring"""

				def 						snake_case	(			self      ):






										"""simple docstring"""

										super().tearDown()
										# Reset the state of the AcceleratorState singleton.
										AcceleratorState._reset_state()
										PartialState._reset_state()





class 					lowerCAmelCase_      (     unittest.TestCase   ):



				"""simple docstring"""

				def 						snake_case	(			self						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     mocks if isinstance(lowerCAmelCase						,      (tuple, list)      ) else [mocks]
										for m in self.mocks:
																m.start()
																self.addCleanup(m.stop      )





def 				lowerCAmelCase__      (     _UpperCamelCase    :			int   )   ->			Any:





						"""simple docstring"""






						snake_case        =     AcceleratorState()
						snake_case        =     tensor[None].clone().to(state.device   )
						snake_case        =     gather(_UpperCamelCase   ).cpu()
						snake_case        =     tensor[0].cpu()
						for i in range(tensors.shape[0]   ):
												if not torch.equal(tensors[i]	,     _UpperCamelCase   ):
																		return False
						return True



class 					lowerCAmelCase_      :



				"""simple docstring"""

				def __init__(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     returncode
										snake_case        =     stdout
										snake_case        =     stderr





async def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict	,     _UpperCamelCase    :			Any   )   ->			List[Any]:





						"""simple docstring"""






						while True:
												snake_case        =     await stream.readline()
												if line:
																		callback(_UpperCamelCase   )
												else:
																		break





async def 				lowerCAmelCase__      (     _UpperCamelCase    :			Optional[Any]	,     _UpperCamelCase    :			Optional[Any]=None	,     _UpperCamelCase    :			List[Any]=None	,     _UpperCamelCase    :			Optional[Any]=None	,     _UpperCamelCase    :			List[str]=False	,     _UpperCamelCase    :			Optional[int]=False   )   ->			_RunOutput:





						"""simple docstring"""






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

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

						# 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)

						snake_case        =     []
						snake_case        =     []

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

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





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[Any]	,     _UpperCamelCase    :			str=None	,     _UpperCamelCase    :			List[str]=None	,     _UpperCamelCase    :			Tuple=1_8_0	,     _UpperCamelCase    :			Dict=False	,     _UpperCamelCase    :			Optional[Any]=True   )   ->			_RunOutput:





						"""simple docstring"""






						snake_case        =     asyncio.get_event_loop()
						snake_case        =     loop.run_until_complete(
						    _stream_subprocess(_UpperCamelCase	,     env=_UpperCamelCase	,     stdin=_UpperCamelCase	,     timeout=_UpperCamelCase	,     quiet=_UpperCamelCase	,     echo=_UpperCamelCase   )   )

						snake_case        =     ' '.join(_UpperCamelCase   )
						if result.returncode > 0:
												snake_case        =     '\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 					lowerCAmelCase_      (     lowerCAmelCase   ):



				"""simple docstring"""
				pass





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[str]	,     _UpperCamelCase    :			Optional[Any]=False   )   ->			Optional[Any]:





						"""simple docstring"""






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


