






import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
 from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase=None    ,      __lowercase=None    ,      __lowercase=None    ,      __lowercase=None    ,      __lowercase=None    ,      ):
   if attention_mask is None:
      UpperCamelCase_									=     input_ids.ne(config.pad_token_id)
   if decoder_attention_mask is None:
      UpperCamelCase_									=     decoder_input_ids.ne(config.pad_token_id)
   if head_mask is None:
      UpperCamelCase_									=     torch.ones(config.encoder_layers    ,      config.encoder_attention_heads    ,      device=__lowercase)
   if decoder_head_mask is None:
      UpperCamelCase_									=     torch.ones(config.decoder_layers    ,      config.decoder_attention_heads    ,      device=__lowercase)
   if cross_attn_head_mask is None:
      UpperCamelCase_									=     torch.ones(config.decoder_layers    ,      config.decoder_attention_heads    ,      device=__lowercase)
   return {
       "input_ids": input_ids,
       "decoder_input_ids": decoder_input_ids,
       "attention_mask": attention_mask,
       "decoder_attention_mask": attention_mask,
       "head_mask": head_mask,
       "decoder_head_mask": decoder_head_mask,
       "cross_attn_head_mask": cross_attn_head_mask,
   }


class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=7		,		_UpperCAmelCase=True		,		_UpperCAmelCase=False		,		_UpperCAmelCase=99		,		_UpperCAmelCase=16		,		_UpperCAmelCase=2		,		_UpperCAmelCase=4		,		_UpperCAmelCase=4		,		_UpperCAmelCase="relu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=20		,		_UpperCAmelCase=2		,		_UpperCAmelCase=1		,		_UpperCAmelCase=0		,		)			-> Any:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     seq_length
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     encoder_layerdrop
     UpperCamelCase_									=     decoder_layerdrop
     UpperCamelCase_									=     max_position_embeddings
     UpperCamelCase_									=     eos_token_id
     UpperCamelCase_									=     pad_token_id
     UpperCamelCase_									=     bos_token_id




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size )
     UpperCamelCase_									=     self.eos_token_id  # Eos Token
     UpperCamelCase_									=     ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size )

     # we need to clamp the input ids here to avoid having pad token in between
     # this is because for M2M100 the position_ids are prepared such that
     # all pad tokens have pos id = 2 and rest are between 2..seq_length
     # and the seq_length here is seq_length - num_pad_tokens
     # but when using past, there is no way of knowing if the past input ids had
     # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
     # position_ids being off by num_pad_tokens in past input
     UpperCamelCase_									=     input_ids.clamp(self.pad_token_id + 1 )
     UpperCamelCase_									=     decoder_input_ids.clamp(self.pad_token_id + 1 )

     UpperCamelCase_									=     self.get_config()
     UpperCamelCase_									=     prepare_mam_aaa_inputs_dict(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
     return config, inputs_dict




  def    _UpperCAmelCase     (     self )			-> Tuple:
     return MaMaaaConfig(
         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		,		encoder_layerdrop=self.encoder_layerdrop		,		decoder_layerdrop=self.decoder_layerdrop		,		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		,		)




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.prepare_config_and_inputs()
     return config, inputs_dict




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Tuple:
     UpperCamelCase_									=     MaMaaaModel(config=_UpperCAmelCase ).get_decoder().to(_UpperCAmelCase ).eval()
     UpperCamelCase_									=     inputs_dict['input_ids']
     UpperCamelCase_									=     inputs_dict['attention_mask']
     UpperCamelCase_									=     inputs_dict['head_mask']

     # first forward pass
     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		head_mask=_UpperCAmelCase		,		use_cache=_UpperCAmelCase )

     UpperCamelCase_		,      UpperCamelCase_									=     outputs.to_tuple()

     # create hypothetical multiple next token and extent to next_input_ids
     UpperCamelCase_									=     ids_tensor((self.batch_size, 3)		,		config.vocab_size )
     UpperCamelCase_									=     ids_tensor((self.batch_size, 3)		,		2 )

     # append to next input_ids and
     UpperCamelCase_									=     torch.cat([input_ids, next_tokens]		,		dim=-1 )
     UpperCamelCase_									=     torch.cat([attention_mask, next_attn_mask]		,		dim=-1 )

     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )['last_hidden_state']
     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		past_key_values=_UpperCAmelCase )[
         'last_hidden_state'
     ]

     # select random slice
     UpperCamelCase_									=     ids_tensor((1,)		,		output_from_past.shape[-1] ).item()
     UpperCamelCase_									=     output_from_no_past[:, -3:, random_slice_idx].detach()
     UpperCamelCase_									=     output_from_past[:, :, random_slice_idx].detach()

     self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )

     # test that outputs are equal for slice
     self.parent.assertTrue(torch.allclose(_UpperCAmelCase		,		_UpperCAmelCase		,		atol=1e-2 ) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_									=     MaMaaaModel(config=_UpperCAmelCase ).to(_UpperCAmelCase ).eval()
     UpperCamelCase_									=     model(**_UpperCAmelCase )

     UpperCamelCase_									=     outputs.encoder_last_hidden_state
     UpperCamelCase_									=     outputs.last_hidden_state

     with tempfile.TemporaryDirectory() as tmpdirname:
        UpperCamelCase_									=     model.get_encoder()
        encoder.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     MaMaaaEncoder.from_pretrained(_UpperCAmelCase ).to(_UpperCAmelCase )

     UpperCamelCase_									=     encoder(inputs_dict['input_ids']		,		attention_mask=inputs_dict['attention_mask'] )[
         0
     ]

     self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 )

     with tempfile.TemporaryDirectory() as tmpdirname:
        UpperCamelCase_									=     model.get_decoder()
        decoder.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     MaMaaaDecoder.from_pretrained(_UpperCAmelCase ).to(_UpperCAmelCase )

     UpperCamelCase_									=     decoder(
         input_ids=inputs_dict['decoder_input_ids']		,		attention_mask=inputs_dict['decoder_attention_mask']		,		encoder_hidden_states=_UpperCAmelCase		,		encoder_attention_mask=inputs_dict['attention_mask']		,		)[0]

     self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 )




@require_torch
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (
      (
          MaMaaaModel,
          MaMaaaForConditionalGeneration,
      )
      if is_torch_available()
      else ()
  )
  A_						=   (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
  A_						=   (
      {
          """conversational""": MaMaaaForConditionalGeneration,
          """feature-extraction""": MaMaaaModel,
          """summarization""": MaMaaaForConditionalGeneration,
          """text2text-generation""": MaMaaaForConditionalGeneration,
          """translation""": MaMaaaForConditionalGeneration,
      }
      if is_torch_available()
      else {}
  )
  A_						=   True
  A_						=   True
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Any:
     if pipeline_test_casse_name == "TranslationPipelineTests":
        # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
        # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
        return True

     return False




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     MaMaaaModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     self.config_tester.run_common_tests()




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )

        with tempfile.TemporaryDirectory() as tmpdirname:
           model.save_pretrained(_UpperCAmelCase )
           UpperCamelCase_		,      UpperCamelCase_									=     model_class.from_pretrained(_UpperCAmelCase		,		output_loading_info=_UpperCAmelCase )
        self.assertEqual(info['missing_keys']		,		[] )




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_decoder_model_past_large_inputs(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_encoder_decoder_model_standalone(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        model.to(_UpperCAmelCase )
        model.eval()

        UpperCamelCase_									=     copy.deepcopy(self._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase ) )

        if not self.is_encoder_decoder:
           UpperCamelCase_									=     inputs['input_ids']
           del inputs["input_ids"]
        else:
           UpperCamelCase_									=     inputs['input_ids']
           UpperCamelCase_									=     inputs.get('decoder_input_ids'		,		_UpperCAmelCase )
           del inputs["input_ids"]
           inputs.pop('decoder_input_ids'		,		_UpperCAmelCase )

        UpperCamelCase_									=     model.get_input_embeddings()
        if not self.is_encoder_decoder:
           UpperCamelCase_									=     wte(_UpperCAmelCase )
        else:
           UpperCamelCase_									=     wte(_UpperCAmelCase )
           UpperCamelCase_									=     wte(_UpperCAmelCase )

        with torch.no_grad():
           model(**_UpperCAmelCase )[0]




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     UpperCamelCase_									=     input_dict['input_ids']
     UpperCamelCase_									=     input_ids.ne(1 ).to(_UpperCAmelCase )
     UpperCamelCase_									=     MaMaaaForConditionalGeneration(_UpperCAmelCase ).eval().to(_UpperCAmelCase )
     if torch_device == "cuda":
        model.half()
     model.generate(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )
     model.generate(num_beams=4		,		do_sample=_UpperCAmelCase		,		early_stopping=_UpperCAmelCase		,		num_return_sequences=3 )






def     _snake_case    (__lowercase):
   return torch.tensor(__lowercase    ,      dtype=torch.long    ,      device=__lowercase)


snake_case__      :	Tuple       	=      1E-4


@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     MaMaaaModel.from_pretrained('facebook/m2m100_418M' ).to(_UpperCAmelCase )
     UpperCamelCase_									=     _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] )
     UpperCamelCase_									=     _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] )
     UpperCamelCase_									=     prepare_mam_aaa_inputs_dict(model.config		,		_UpperCAmelCase		,		_UpperCAmelCase )
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )[0]
     UpperCamelCase_									=     torch.Size((1, 11, 1024) )
     self.assertEqual(output.shape		,		_UpperCAmelCase )
     # change to expected output here
     UpperCamelCase_									=     torch.tensor(
         [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]]		,		device=_UpperCAmelCase )
     self.assertTrue(torch.allclose(output[:, :3, :3]		,		_UpperCAmelCase		,		atol=_UpperCAmelCase ) )




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(_UpperCAmelCase )

     # change to intended input
     UpperCamelCase_									=     _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] )
     UpperCamelCase_									=     _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] )
     UpperCamelCase_									=     prepare_mam_aaa_inputs_dict(model.config		,		_UpperCAmelCase		,		_UpperCAmelCase )
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )[0]
     UpperCamelCase_									=     torch.Size((1, 11, model.config.vocab_size) )
     self.assertEqual(output.shape		,		_UpperCAmelCase )
     # change to expected output here
     UpperCamelCase_									=     torch.tensor(
         [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]]		,		device=_UpperCAmelCase )
     self.assertTrue(torch.allclose(output[:, :3, :3]		,		_UpperCAmelCase		,		atol=_UpperCAmelCase ) )




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(_UpperCAmelCase )
     UpperCamelCase_									=     MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'		,		src_lang='fr'		,		tgt_lang='en' )

     UpperCamelCase_									=     [
         'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
         'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
         'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
         ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
         ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
     ]

     # The below article tests that we don't add any hypotheses outside of the top n_beams
     UpperCamelCase_									=     tokenizer(_UpperCAmelCase		,		padding=_UpperCAmelCase		,		return_tensors='pt' )

     UpperCamelCase_									=     model.generate(
         input_ids=dct['input_ids'].to(_UpperCAmelCase )		,		attention_mask=dct['attention_mask'].to(_UpperCAmelCase )		,		num_beams=5		,		forced_bos_token_id=tokenizer.get_lang_id('en' )		,		)

     UpperCamelCase_									=     [
         'The NSA case highlights the total absence of intelligence debate',
         'I think there are two levels of response from the French government.',
         'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
         ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
         ' communications in France.',
     ]

     UpperCamelCase_									=     tokenizer.batch_decode(
         hypotheses_batch.tolist()		,		clean_up_tokenization_spaces=_UpperCAmelCase		,		skip_special_tokens=_UpperCAmelCase )
     assert generated == expected_en













import inspect
import os
import unittest
from pathlib import Path

import torch

import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command


class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  A_						=   inspect.getfile(accelerate.test_utils    )
  A_						=   os.path.sep.join(mod_file.split(os.path.sep    )[:-1] + ["""scripts""", """test_cli.py"""]    )

  A_						=   ["""accelerate""", """launch"""]
  A_						=   Path.home() / """.cache/huggingface/accelerate"""
  A_						=   """default_config.yaml"""
  A_						=   config_folder / config_file
  A_						=   config_folder / """_default_config.yaml"""

  A_						=   Path("""tests/test_configs"""    )




  @classmethod
  def    _UpperCAmelCase     (     cls )			-> Union[str, Any]:
     if cls.config_path.is_file():
        cls.config_path.rename(cls.changed_path )




  @classmethod
  def    _UpperCAmelCase     (     cls )			-> List[str]:
     if cls.changed_path.is_file():
        cls.changed_path.rename(cls.config_path )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     self.base_cmd
     if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
        cmd += ["--multi_gpu"]
     execute_subprocess_async(cmd + [self.test_file_path]		,		env=os.environ.copy() )




  def    _UpperCAmelCase     (     self )			-> Optional[int]:
     for config in sorted(self.test_config_path.glob('**/*.yaml' ) ):
        with self.subTest(config_file=_UpperCAmelCase ):
           execute_subprocess_async(
               self.base_cmd + ['--config_file', str(_UpperCAmelCase ), self.test_file_path]		,		env=os.environ.copy() )




  def    _UpperCAmelCase     (     self )			-> Tuple:
     execute_subprocess_async(['accelerate', 'test']		,		env=os.environ.copy() )




class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  A_						=   """test-tpu"""
  A_						=   """us-central1-a"""
  A_						=   """ls"""
  A_						=   ["""accelerate""", """tpu-config"""]
  A_						=   """cd /usr/share"""
  A_						=   """tests/test_samples/test_command_file.sh"""
  A_						=   """Running gcloud compute tpus tpu-vm ssh"""




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     run_command(
         self.cmd
         + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug']		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     run_command(
         self.cmd
         + [
             '--config_file',
             'tests/test_configs/0_12_0.yaml',
             '--command',
             self.command,
             '--tpu_zone',
             self.tpu_zone,
             '--tpu_name',
             self.tpu_name,
             '--debug',
         ]		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     run_command(
         self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug']		,		return_stdout=_UpperCAmelCase )
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     run_command(
         self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug']		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     run_command(
         self.cmd
         + [
             '--config_file',
             'tests/test_configs/latest.yaml',
             '--command',
             self.command,
             '--command',
             'echo "Hello World"',
             '--debug',
         ]		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     run_command(
         self.cmd
         + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug']		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     run_command(
         self.cmd
         + [
             '--config_file',
             'tests/test_configs/0_12_0.yaml',
             '--command_file',
             self.command_file,
             '--tpu_zone',
             self.tpu_zone,
             '--tpu_name',
             self.tpu_name,
             '--debug',
         ]		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     run_command(
         self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug']		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all"""		,		_UpperCAmelCase		,		)




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     run_command(
         self.cmd
         + [
             '--config_file',
             'tests/test_configs/latest.yaml',
             '--install_accelerate',
             '--accelerate_version',
             '12.0.0',
             '--debug',
         ]		,		return_stdout=_UpperCAmelCase		,		)
     self.assertIn(
         f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all"""		,		_UpperCAmelCase		,		)





