






import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotConfig, is_flax_available
from transformers.testing_utils import jax_device, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
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
		UpperCamelCase 				=	'''platform'''

		import jax
		import jax.numpy as jnp

		from transformers import BlenderbotTokenizer
		from transformers.models.blenderbot.modeling_flax_blenderbot import (
		    FlaxBlenderbotForConditionalGeneration,
		    FlaxBlenderbotModel,
		    shift_tokens_right,
		)

def        __lowerCamelCase			(		snake_case__       ,snake_case__       ,snake_case__=None       ,snake_case__=None       ,snake_case__=None       ,snake_case__=None       ,snake_case__=None       ,snake_case__=None       ,)							->  Any:






						"""simple docstring"""





						if attention_mask is None:
												_SCREAMING_SNAKE_CASE	      =  np.where(input_ids != config.pad_token_id       ,1       ,0		)
						if decoder_attention_mask is None:
												_SCREAMING_SNAKE_CASE	      =  np.where(decoder_input_ids != config.pad_token_id       ,1       ,0		)
						if head_mask is None:
												_SCREAMING_SNAKE_CASE	      =  np.ones((config.encoder_layers, config.encoder_attention_heads)		)
						if decoder_head_mask is None:
												_SCREAMING_SNAKE_CASE	      =  np.ones((config.decoder_layers, config.decoder_attention_heads)		)
						if cross_attn_head_mask is None:
												_SCREAMING_SNAKE_CASE	      =  np.ones((config.decoder_layers, config.decoder_attention_heads)		)
						return {
						    "input_ids": input_ids,
						    "decoder_input_ids": decoder_input_ids,
						    "attention_mask": attention_mask,
						    "decoder_attention_mask": attention_mask,
						}



class       __UpperCAmelCase		:







			def __init__(	self:  Any      ,	UpperCAmelCase_:  Union[str, Any]      ,	UpperCAmelCase_:  List[Any]=13      ,	UpperCAmelCase_:  int=7      ,	UpperCAmelCase_:  Dict=True      ,	UpperCAmelCase_:  int=False      ,	UpperCAmelCase_:  Any=99      ,	UpperCAmelCase_:  Tuple=16      ,	UpperCAmelCase_:  Optional[int]=2      ,	UpperCAmelCase_:  Optional[int]=4      ,	UpperCAmelCase_:  Dict=4      ,	UpperCAmelCase_:  List[str]="gelu"      ,	UpperCAmelCase_:  List[Any]=0.1      ,	UpperCAmelCase_:  List[Any]=0.1      ,	UpperCAmelCase_:  Any=32      ,	UpperCAmelCase_:  int=2      ,	UpperCAmelCase_:  Union[str, Any]=1      ,	UpperCAmelCase_:  int=0      ,	UpperCAmelCase_:  Dict=0.02      ,	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  parent
									_SCREAMING_SNAKE_CASE	      =  batch_size
									_SCREAMING_SNAKE_CASE	      =  seq_length
									_SCREAMING_SNAKE_CASE	      =  is_training
									_SCREAMING_SNAKE_CASE	      =  use_labels
									_SCREAMING_SNAKE_CASE	      =  vocab_size
									_SCREAMING_SNAKE_CASE	      =  hidden_size
									_SCREAMING_SNAKE_CASE	      =  num_hidden_layers
									_SCREAMING_SNAKE_CASE	      =  num_attention_heads
									_SCREAMING_SNAKE_CASE	      =  intermediate_size
									_SCREAMING_SNAKE_CASE	      =  hidden_act
									_SCREAMING_SNAKE_CASE	      =  hidden_dropout_prob
									_SCREAMING_SNAKE_CASE	      =  attention_probs_dropout_prob
									_SCREAMING_SNAKE_CASE	      =  max_position_embeddings
									_SCREAMING_SNAKE_CASE	      =  eos_token_id
									_SCREAMING_SNAKE_CASE	      =  pad_token_id
									_SCREAMING_SNAKE_CASE	      =  bos_token_id
									_SCREAMING_SNAKE_CASE	      =  initializer_range







			def 							UpperCamelCase      (	self:  Union[str, Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  np.clip(ids_tensor([self.batch_size, self.seq_length - 1]      ,	self.vocab_size     )      ,	3      ,	self.vocab_size     )
									_SCREAMING_SNAKE_CASE	      =  np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)      ,	dtype=np.intaa     ))      ,	-1     )

									_SCREAMING_SNAKE_CASE	      =  shift_tokens_right(UpperCAmelCase_      ,	1      ,	2     )

									_SCREAMING_SNAKE_CASE	      =  BlenderbotConfig(
									    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_id=self.eos_token_id      ,	bos_token_id=self.bos_token_id      ,	pad_token_id=self.pad_token_id      ,	initializer_range=self.initializer_range      ,	use_cache=UpperCAmelCase_      ,	)
									_SCREAMING_SNAKE_CASE	      =  prepare_blenderbot_inputs_dict(UpperCAmelCase_      ,	UpperCAmelCase_      ,	UpperCAmelCase_     )
									return config, inputs_dict







			def 							UpperCamelCase      (	self:  Any     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  self.prepare_config_and_inputs()
									return config, inputs_dict







			def 							UpperCamelCase      (	self:  str      ,	UpperCAmelCase_:  Tuple      ,	UpperCAmelCase_:  Tuple      ,	UpperCAmelCase_:  List[str]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  20
									_SCREAMING_SNAKE_CASE	      =  model_class_name(UpperCAmelCase_     )

									_SCREAMING_SNAKE_CASE	      =  model.encode(inputs_dict["""input_ids"""]     )

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

									_SCREAMING_SNAKE_CASE	      =  model.init_cache(decoder_input_ids.shape[0]      ,	UpperCAmelCase_      ,	UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  jnp.ones((decoder_input_ids.shape[0], max_decoder_length)      ,	dtype="""i4"""     )

									_SCREAMING_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)      ,	)
									_SCREAMING_SNAKE_CASE	      =  model.decode(
									    decoder_input_ids[:, :-1]      ,	UpperCAmelCase_      ,	decoder_attention_mask=UpperCAmelCase_      ,	past_key_values=UpperCAmelCase_      ,	decoder_position_ids=UpperCAmelCase_      ,	)

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

									_SCREAMING_SNAKE_CASE	      =  model.decode(UpperCAmelCase_      ,	UpperCAmelCase_     )

									_SCREAMING_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 							UpperCamelCase      (	self:  Union[str, Any]      ,	UpperCAmelCase_:  Dict      ,	UpperCAmelCase_:  Union[str, Any]      ,	UpperCAmelCase_:  Dict     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  20
									_SCREAMING_SNAKE_CASE	      =  model_class_name(UpperCAmelCase_     )

									_SCREAMING_SNAKE_CASE	      =  model.encode(inputs_dict["""input_ids"""]     )

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

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

									_SCREAMING_SNAKE_CASE	      =  model.init_cache(decoder_input_ids.shape[0]      ,	UpperCAmelCase_      ,	UpperCAmelCase_     )
									_SCREAMING_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)      ,	)

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

									_SCREAMING_SNAKE_CASE	      =  model.decode(UpperCAmelCase_      ,	UpperCAmelCase_      ,	decoder_attention_mask=UpperCAmelCase_     )

									_SCREAMING_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}'     )



@require_flax
class       __UpperCAmelCase		(unittest.TestCase    ):
			__snake_case				:      Dict 						=							99







			def 							UpperCamelCase      (	self:  Dict     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  np.array(
									    [
									        [71, 82, 18, 33, 46, 91, 2],
									        [68, 34, 26, 58, 30, 82, 2],
									        [5, 97, 17, 39, 94, 40, 2],
									        [76, 83, 94, 25, 70, 78, 2],
									        [87, 59, 41, 35, 48, 66, 2],
									        [55, 13, 16, 58, 5, 2, 1],  # note padding
									        [64, 27, 31, 51, 12, 75, 2],
									        [52, 64, 86, 17, 83, 39, 2],
									        [48, 61, 9, 24, 71, 82, 2],
									        [26, 1, 60, 48, 22, 13, 2],
									        [21, 5, 62, 28, 14, 76, 2],
									        [45, 98, 37, 86, 59, 48, 2],
									        [70, 70, 50, 9, 28, 0, 2],
									    ]      ,	dtype=np.intaa      ,	)

									_SCREAMING_SNAKE_CASE	      =  input_ids.shape[0]
									_SCREAMING_SNAKE_CASE	      =  BlenderbotConfig(
									    vocab_size=self.vocab_size      ,	d_model=24      ,	encoder_layers=2      ,	decoder_layers=2      ,	encoder_attention_heads=2      ,	decoder_attention_heads=2      ,	encoder_ffn_dim=32      ,	decoder_ffn_dim=32      ,	max_position_embeddings=48      ,	eos_token_id=2      ,	pad_token_id=1      ,	bos_token_id=0      ,	)
									return config, input_ids, batch_size







			def 							UpperCamelCase      (	self:  Optional[Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  self._get_config_and_data()
									_SCREAMING_SNAKE_CASE	      =  FlaxBlenderbotForConditionalGeneration(UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  lm_model(input_ids=UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  (batch_size, input_ids.shape[1], config.vocab_size)
									self.assertEqual(outputs["""logits"""].shape      ,	UpperCAmelCase_     )







			def 							UpperCamelCase      (	self:  Tuple     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  BlenderbotConfig(
									    vocab_size=self.vocab_size      ,	d_model=14      ,	encoder_layers=2      ,	decoder_layers=2      ,	encoder_attention_heads=2      ,	decoder_attention_heads=2      ,	encoder_ffn_dim=8      ,	decoder_ffn_dim=8      ,	max_position_embeddings=48      ,	)
									_SCREAMING_SNAKE_CASE	      =  FlaxBlenderbotForConditionalGeneration(UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]]      ,	dtype=np.intaa     )
									_SCREAMING_SNAKE_CASE	      =  np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]]      ,	dtype=np.intaa     )
									_SCREAMING_SNAKE_CASE	      =  lm_model(input_ids=UpperCAmelCase_      ,	decoder_input_ids=UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  (*summary.shape, config.vocab_size)
									self.assertEqual(outputs["""logits"""].shape      ,	UpperCAmelCase_     )







			def 							UpperCamelCase      (	self:  Optional[Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]]      ,	dtype=np.intaa     )
									_SCREAMING_SNAKE_CASE	      =  shift_tokens_right(UpperCAmelCase_      ,	1      ,	2     )
									_SCREAMING_SNAKE_CASE	      =  np.equal(UpperCAmelCase_      ,	1     ).astype(np.floataa     ).sum()
									_SCREAMING_SNAKE_CASE	      =  np.equal(UpperCAmelCase_      ,	1     ).astype(np.floataa     ).sum()
									self.assertEqual(shifted.shape      ,	input_ids.shape     )
									self.assertEqual(UpperCAmelCase_      ,	n_pad_before - 1     )
									self.assertTrue(np.equal(shifted[:, 0]      ,	2     ).all()     )



@require_flax
class       __UpperCAmelCase		(snake_case_       ,unittest.TestCase       ,snake_case_    ):
			__snake_case				:      List[Any] 						=							True
			__snake_case				:      str 						=							(
			    (
			        FlaxBlenderbotModel,
			        FlaxBlenderbotForConditionalGeneration,
			    )
			    if is_flax_available()
			    else ()
			)
			__snake_case				:      List[str] 						=							(FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else ()







			def 							UpperCamelCase      (	self:  List[Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  FlaxBlenderbotModelTester(self     )







			def 							UpperCamelCase      (	self:  Optional[Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
															self.model_tester.check_use_cache_forward(UpperCAmelCase_      ,	UpperCAmelCase_      ,	UpperCAmelCase_     )







			def 							UpperCamelCase      (	self:  Dict     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
															self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase_      ,	UpperCAmelCase_      ,	UpperCAmelCase_     )







			def 							UpperCamelCase      (	self:  Tuple     ):







									'''simple docstring'''




									_SCREAMING_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__     ):
																					_SCREAMING_SNAKE_CASE	      =  self._prepare_for_class(UpperCAmelCase_      ,	UpperCAmelCase_     )
																					_SCREAMING_SNAKE_CASE	      =  model_class(UpperCAmelCase_     )

																					@jax.jit
																					def encode_jitted(UpperCAmelCase_:  Optional[Any]      ,	UpperCAmelCase_:  Optional[Any]=None      ,	**UpperCAmelCase_:  List[Any]     ):
																											return model.encode(input_ids=UpperCAmelCase_      ,	attention_mask=UpperCAmelCase_     )

																					with self.subTest("""JIT Enabled"""     ):
																											_SCREAMING_SNAKE_CASE	      =  encode_jitted(**UpperCAmelCase_     ).to_tuple()

																					with self.subTest("""JIT Disabled"""     ):
																											with jax.disable_jit():
																																	_SCREAMING_SNAKE_CASE	      =  encode_jitted(**UpperCAmelCase_     ).to_tuple()

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







			def 							UpperCamelCase      (	self:  int     ):







									'''simple docstring'''




									_SCREAMING_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__     ):
																					_SCREAMING_SNAKE_CASE	      =  model_class(UpperCAmelCase_     )
																					_SCREAMING_SNAKE_CASE	      =  model.encode(inputs_dict["""input_ids"""]      ,	inputs_dict["""attention_mask"""]     )

																					_SCREAMING_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(UpperCAmelCase_:  List[Any]      ,	UpperCAmelCase_:  Union[str, Any]      ,	UpperCAmelCase_:  Any     ):
																											return model.decode(
																											    decoder_input_ids=UpperCAmelCase_      ,	decoder_attention_mask=UpperCAmelCase_      ,	encoder_outputs=UpperCAmelCase_      ,	)

																					with self.subTest("""JIT Enabled"""     ):
																											_SCREAMING_SNAKE_CASE	      =  decode_jitted(**UpperCAmelCase_     ).to_tuple()

																					with self.subTest("""JIT Disabled"""     ):
																											with jax.disable_jit():
																																	_SCREAMING_SNAKE_CASE	      =  decode_jitted(**UpperCAmelCase_     ).to_tuple()

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







			@slow
			def 							UpperCamelCase      (	self:  int     ):







									'''simple docstring'''




									for model_class_name in self.all_model_classes:
															_SCREAMING_SNAKE_CASE	      =  model_class_name.from_pretrained("""facebook/blenderbot-400M-distill"""     )
															# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
															_SCREAMING_SNAKE_CASE	      =  np.ones((1, 1)     ) * model.config.eos_token_id
															_SCREAMING_SNAKE_CASE	      =  model(UpperCAmelCase_     )
															self.assertIsNotNone(UpperCAmelCase_     )







			@unittest.skipUnless(jax_device != """cpu"""      ,	"""3B test too slow on CPU."""     )
			@slow
			def 							UpperCamelCase      (	self:  List[str]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  {'num_beams': 1, 'early_stopping': True, 'min_length': 15, 'max_length': 25}
									_SCREAMING_SNAKE_CASE	      =  {'skip_special_tokens': True, 'clean_up_tokenization_spaces': True}

									_SCREAMING_SNAKE_CASE	      =  FlaxBlenderbotForConditionalGeneration.from_pretrained("""facebook/blenderbot-3B"""      ,	from_pt=UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  BlenderbotTokenizer.from_pretrained("""facebook/blenderbot-3B"""     )

									_SCREAMING_SNAKE_CASE	      =  ['Sam']
									_SCREAMING_SNAKE_CASE	      =  tokenizer(UpperCAmelCase_      ,	return_tensors="""jax"""     )

									_SCREAMING_SNAKE_CASE	      =  model.generate(**UpperCAmelCase_      ,	**UpperCAmelCase_     )
									_SCREAMING_SNAKE_CASE	      =  'Sam is a great name. It means "sun" in Gaelic.'

									_SCREAMING_SNAKE_CASE	      =  tokenizer.batch_decode(UpperCAmelCase_      ,	**UpperCAmelCase_     )
									assert generated_txt[0].strip() == tgt_text


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     (						lowerCamelCase					:     Dict  ,  lowerCamelCase					:     int=False	):
 try:
  UpperCamelCase_					:						Union[str, Any] =					os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  UpperCamelCase_					:						List[str] =					default
 else:
  # KEY is set, convert it to True or False.
  try:
   UpperCamelCase_					:						Union[str, Any] =					strtobool(lowerCamelCase	)
  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


a_    					=       parse_flag_from_env('RUN_SLOW', default=False)





def    __lowercase     (						lowerCamelCase					:     List[Any]	):
 return unittest.skip('Test was skipped'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(_run_slow_tests  ,  'test is slow'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(not torch.cuda.is_available()  ,  'test requires only a CPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Optional[Any]	):
 return unittest.skipUnless(torch.cuda.is_available()  ,  'test requires a GPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_xpu_available()  ,  'test requires a XPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_mps_available()  ,  'test requires a `mps` backend support in `torch`'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(
     is_transformers_available() and is_datasets_available()  ,  'test requires the Hugging Face suite'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[str]	):
 return unittest.skipUnless(is_bnb_available()  ,  'test requires the bitsandbytes library'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(is_tpu_available()  ,  'test requires TPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(torch.cuda.device_count() == 1  ,  'test requires a GPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(torch.xpu.device_count() == 1  ,  'test requires a XPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Optional[Any]	):
 return unittest.skipUnless(torch.cuda.device_count() > 1  ,  'test requires multiple GPUs'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[Any]	):
 return unittest.skipUnless(torch.xpu.device_count() > 1  ,  'test requires multiple XPUs'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_safetensors_available()  ,  'test requires safetensors'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_deepspeed_available()  ,  'test requires DeepSpeed'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(is_torch_version('>='  ,  '1.12.0'	)  ,  'test requires torch version >= 1.12.0'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[Any]=None  ,  lowerCamelCase					:     Optional[int]=None	):
 if test_case is None:
  return partial(lowerCamelCase  ,  version=lowerCamelCase	)
 return unittest.skipUnless(is_torch_version('>='  ,  lowerCamelCase	)  ,  F"test requires torch version >= {version}"	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_tensorboard_available()  ,  'test requires Tensorboard'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_wandb_available()  ,  'test requires wandb'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Dict	):
 return unittest.skipUnless(is_comet_ml_available()  ,  'test requires comet_ml'	)(lowerCamelCase	)


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





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





class 		_lowercase						(					unittest.TestCase       ):
 lowercase				     =   True

 @classmethod
 def 						SCREAMING_SNAKE_CASE__   ( cls	:							Union[str, Any]			)   ->						Union[str, Any]:

  """simple docstring"""





  UpperCamelCase_					:						str =					tempfile.mkdtemp()

 @classmethod
 def 						SCREAMING_SNAKE_CASE__   ( cls	:							Any			)   ->						Union[str, Any]:

  """simple docstring"""





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


 def 						SCREAMING_SNAKE_CASE__   ( self	:							str			)   ->						List[str]:

  """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(snake_case			)





class 		_lowercase						(					unittest.TestCase       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Any:

  """simple docstring"""





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





class 		_lowercase						(					unittest.TestCase       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str   ,      snake_case	:							Union[mock.Mock, List[mock.Mock]]			)   ->						Optional[int]:

  """simple docstring"""





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





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





class 		_lowercase						:

 def __init__( self	:							Optional[int]   ,      snake_case	:							Any   ,      snake_case	:							List[Any]   ,      snake_case	:							int			)   ->						Optional[int]:

  """simple docstring"""





  UpperCamelCase_					:						int =					returncode
  UpperCamelCase_					:						Optional[int] =					stdout
  UpperCamelCase_					:						Optional[int] =					stderr





async def    __lowercase     (						lowerCamelCase					:     Optional[Any]  ,  lowerCamelCase					:     Tuple	):
 while True:
  UpperCamelCase_					:						Tuple =					await stream.readline()
  if line:
   callback(lowerCamelCase	)
  else:
   break





async def    __lowercase     (						lowerCamelCase					:     Dict  ,  lowerCamelCase					:     Dict=None  ,  lowerCamelCase					:     Optional[Any]=None  ,  lowerCamelCase					:     List[str]=None  ,  lowerCamelCase					:     Dict=False  ,  lowerCamelCase					:     Tuple=False	):
 if echo:
  print('\nRunning: '  ,  ' '.join(lowerCamelCase	)	)

 UpperCamelCase_					:						Optional[int] =					await asyncio.create_subprocess_exec(
     cmd[0]  ,  *cmd[1:]  ,  stdin=lowerCamelCase  ,  stdout=asyncio.subprocess.PIPE  ,  stderr=asyncio.subprocess.PIPE  ,  env=lowerCamelCase  ,  )

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

 UpperCamelCase_					:						str =					[]
 UpperCamelCase_					:						Union[str, Any] =					[]

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

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





def    __lowercase     (						lowerCamelCase					:     List[Any]  ,  lowerCamelCase					:     Optional[Any]=None  ,  lowerCamelCase					:     int=None  ,  lowerCamelCase					:     Any=180  ,  lowerCamelCase					:     Dict=False  ,  lowerCamelCase					:     Optional[int]=True	):
 UpperCamelCase_					:						str =					asyncio.get_event_loop()
 UpperCamelCase_					:						Union[str, Any] =					loop.run_until_complete(
     _stream_subprocess(lowerCamelCase  ,  env=lowerCamelCase  ,  stdin=lowerCamelCase  ,  timeout=lowerCamelCase  ,  quiet=lowerCamelCase  ,  echo=lowerCamelCase	)	)

 UpperCamelCase_					:						int =					' '.join(lowerCamelCase	)
 if result.returncode > 0:
  UpperCamelCase_					:						Dict =					'\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						(					snake_case_       ):
 pass





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



