





import argparse
import logging
import os
import sys
import tempfile
from pathlib import Path

import lightning_base
import pytest
import pytorch_lightning as pl
import torch
from convert_pl_checkpoint_to_hf import convert_pl_to_hf
from distillation import distill_main
from finetune import SummarizationModule, main
from huggingface_hub import list_models
from parameterized import parameterized
from run_eval import generate_summaries_or_translations
from torch import nn

from transformers import AutoConfig, AutoModelForSeqaSeqLM
from transformers.testing_utils import CaptureStderr, CaptureStdout, TestCasePlus, require_torch_gpu, slow
from utils import label_smoothed_nll_loss, lmap, load_json


logging.basicConfig(level=logging.DEBUG)

UpperCAmelCase_   				=  logging.getLogger()
UpperCAmelCase_   				=  torch.cuda.is_available()
UpperCAmelCase_   				=  {
    """max_tokens_per_batch""": None,
    """supervise_forward""": True,
    """normalize_hidden""": True,
    """label_smoothing""": 0.2,
    """eval_max_gen_length""": None,
    """eval_beams""": 1,
    """val_metric""": """loss""",
    """save_top_k""": 1,
    """adafactor""": True,
    """early_stopping_patience""": 2,
    """logger_name""": """default""",
    """length_penalty""": 0.5,
    """cache_dir""": """""",
    """task""": """summarization""",
    """num_workers""": 2,
    """alpha_hid""": 0,
    """freeze_embeds""": True,
    """enc_only""": False,
    """tgt_suffix""": """""",
    """resume_from_checkpoint""": None,
    """sortish_sampler""": True,
    """student_decoder_layers""": 1,
    """val_check_interval""": 1.0,
    """output_dir""": """""",
    """fp16""": False,  # TODO(SS): set this to CUDA_AVAILABLE if ci installs apex or start using native amp
    """no_teacher""": False,
    """fp16_opt_level""": """O1""",
    """gpus""": 1 if CUDA_AVAILABLE else 0,
    """n_tpu_cores""": 0,
    """max_grad_norm""": 1.0,
    """do_train""": True,
    """do_predict""": True,
    """accumulate_grad_batches""": 1,
    """server_ip""": """""",
    """server_port""": """""",
    """seed""": 42,
    """model_name_or_path""": """sshleifer/bart-tiny-random""",
    """config_name""": """""",
    """tokenizer_name""": """facebook/bart-large""",
    """do_lower_case""": False,
    """learning_rate""": 0.3,
    """lr_scheduler""": """linear""",
    """weight_decay""": 0.0,
    """adam_epsilon""": 1E-08,
    """warmup_steps""": 0,
    """max_epochs""": 1,
    """train_batch_size""": 2,
    """eval_batch_size""": 2,
    """max_source_length""": 12,
    """max_target_length""": 12,
    """val_max_target_length""": 12,
    """test_max_target_length""": 12,
    """fast_dev_run""": False,
    """no_cache""": False,
    """n_train""": -1,
    """n_val""": -1,
    """n_test""": -1,
    """student_encoder_layers""": 1,
    """freeze_encoder""": False,
    """auto_scale_batch_size""": False,
    """overwrite_output_dir""": False,
    """student""": None,
}





def     lowerCamelCase__  (  UpperCamelCase__      :							Path							,     UpperCamelCase__      :							list    )      ->			str:



					'''simple docstring'''




					_snake_case						=					'\n'.join(UpperCamelCase__    )
					Path(UpperCamelCase__    ).open('w'    ).writelines(UpperCamelCase__    )


UpperCAmelCase_   				=  [""" Sam ate lunch today.""", """Sams lunch ingredients."""]
UpperCAmelCase_   				=  ["""A very interesting story about what I ate for lunch.""", """Avocado, celery, turkey, coffee"""]
UpperCAmelCase_   				=  """patrickvonplaten/t5-tiny-random"""
UpperCAmelCase_   				=  """sshleifer/t5-tinier-random"""
UpperCAmelCase_   				=  """sshleifer/bart-tiny-random"""
UpperCAmelCase_   				=  """sshleifer/tiny-mbart"""
UpperCAmelCase_   				=  """sshleifer/tiny-marian-en-de"""
UpperCAmelCase_   				=  """stas/tiny-wmt19-en-de"""


UpperCAmelCase_   				=  logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logging.disable(logging.CRITICAL)  # remove noisy download output from tracebacks





def     lowerCamelCase__  (  UpperCamelCase__      :							Tuple    )      ->			Dict:



					'''simple docstring'''




					for split in ["train", "val", "test"]:
										_dump_articles(os.path.join(UpperCamelCase__							,     F'''{split}.source'''    )							,     UpperCamelCase__    )
										_dump_articles(os.path.join(UpperCamelCase__							,     F'''{split}.target'''    )							,     UpperCamelCase__    )
					return tmp_dir
class       UpperCamelCase_		(	_lowerCamelCase       ):




					@classmethod
					def 						lowerCAmelCase      (		cls	)		->				Dict:
										logging.disable(logging.CRITICAL	)  # remove noisy download output from tracebacks
										return cls




					@slow
					@require_torch_gpu
					def 						lowerCAmelCase      (		self	)		->				Optional[Any]:
										_snake_case						=					list_models()
										_snake_case						=					'sshleifer'
										_snake_case						=					[x.modelId for x in model_list if x.modelId.startswith(lowerCAmelCase_	)]
										_snake_case						=					['sshleifer/blenderbot-3B', 'sshleifer/blenderbot-90M']
										_snake_case						=					[]
										for m in model_ids:
															if m in allowed_to_be_broken:
																				continue
															try:
																				AutoConfig.from_pretrained(lowerCAmelCase_	)
															except Exception:
																				failures.append(lowerCAmelCase_	)
										assert not failures, F'''The following models could not be loaded through AutoConfig: {failures}'''




					def 						lowerCAmelCase      (		self	)		->				List[str]:
										_snake_case						=					{'student_encoder_layers': 2, 'student_decoder_layers': 1, 'no_teacher': True}
										self._test_distiller_cli(lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self	)		->				List[str]:
										_snake_case						=					{
										    'student_encoder_layers': 2,
										    'student_decoder_layers': 1,
										    'max_epochs': 4,
										    'val_check_interval': 0.25,
										    'alpha_hid': 2.0,
										    'model_name_or_path': 'IGNORE_THIS_IT_DOESNT_GET_USED',
										}
										_snake_case						=					self._test_distiller_cli(lowerCAmelCase_					,    check_contents=lowerCAmelCase_	)

										_snake_case						=					list(Path(model.output_dir	).glob('*.ckpt'	)	)
										self.assertEqual(1					,    len(lowerCAmelCase_	)	)
										_snake_case						=					list(Path(model.output_dir	).glob('**/*.bin'	)	)
										self.assertEqual(len(lowerCAmelCase_	)					,    2	)
										_snake_case						=					lmap(str.strip					,    Path(model.hparams.data_dir	).joinpath('test.source'	).open().readlines()	)
										_snake_case						=					tempfile.mktemp()  # XXX: not being cleaned up
										generate_summaries_or_translations(lowerCAmelCase_					,    lowerCAmelCase_					,    str(model.output_dir / 'best_tfmr'	)	)
										self.assertTrue(Path(lowerCAmelCase_	).exists()	)

										_snake_case						=					self.get_auto_remove_tmp_dir()
										convert_pl_to_hf(ckpts[0]					,    transformer_ckpts[0].parent					,    lowerCAmelCase_	)
										assert os.path.exists(os.path.join(lowerCAmelCase_					,    'pytorch_model.bin'	)	)




					def 						lowerCAmelCase      (		self	)		->				Any:
										_snake_case						=					AutoModelForSeqaSeqLM.from_pretrained(lowerCAmelCase_	)
										_snake_case				,  _snake_case						=					model.dummy_inputs['input_ids'], model.dummy_inputs['attention_mask']
										_snake_case						=					torch.tensor([[0, 4, 8, 2], [0, 8, 2, 1]]					,    dtype=torch.long					,    device=model.device	)
										_snake_case						=					target_ids[:, :-1].contiguous()  # Why this line?
										_snake_case						=					target_ids[:, 1:].clone()  # why clone?
										_snake_case						=					model(
										    lowerCAmelCase_					,    attention_mask=lowerCAmelCase_					,    decoder_input_ids=lowerCAmelCase_					,    labels=lowerCAmelCase_					,    use_cache=lowerCAmelCase_	).loss

										_snake_case						=					model(lowerCAmelCase_					,    attention_mask=lowerCAmelCase_					,    decoder_input_ids=lowerCAmelCase_					,    use_cache=lowerCAmelCase_	).logits

										_snake_case						=					nn.functional.log_softmax(lowerCAmelCase_					,    dim=-1	)
										_snake_case				,  _snake_case						=					label_smoothed_nll_loss(
										    lowerCAmelCase_					,    lowerCAmelCase_					,    0.1					,    ignore_index=model.config.pad_token_id	)
										with self.assertRaises(lowerCAmelCase_	):
															# TODO: understand why this breaks
															self.assertEqual(lowerCAmelCase_					,    lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self	)		->				int:
										_snake_case						=					{
										    'student_encoder_layers': 2,
										    'student_decoder_layers': 1,
										    'num_train_epochs': 4,
										    'val_check_interval': 0.25,
										    'alpha_hid': 2.0,
										    'task': 'translation',
										    'model_name_or_path': 'IGNORE_THIS_IT_DOESNT_GET_USED',
										    'tokenizer_name': MBART_TINY,
										    'teacher': MBART_TINY,
										    'src_lang': 'en_XX',
										    'tgt_lang': 'ro_RO',
										}
										_snake_case						=					self._test_distiller_cli(lowerCAmelCase_					,    check_contents=lowerCAmelCase_	)
										assert model.model.config.model_type == "mbart"

										_snake_case						=					list(Path(model.output_dir	).glob('*.ckpt'	)	)
										self.assertEqual(1					,    len(lowerCAmelCase_	)	)
										_snake_case						=					list(Path(model.output_dir	).glob('**/*.bin'	)	)
										_snake_case						=					list(Path(model.output_dir	).glob('best_tfmr/*'	)	)
										assert len(lowerCAmelCase_	) > 2
										self.assertEqual(len(lowerCAmelCase_	)					,    2	)




					def 						lowerCAmelCase      (		self	)		->				Optional[int]:
										_snake_case						=					{
										    'student_encoder_layers': 1,
										    'student_decoder_layers': 1,
										    'alpha_hid': 2.0,
										    'teacher': T5_TINY,
										    'model_name_or_path': T5_TINY,
										    'tokenizer_name': T5_TINY,
										}
										self._test_distiller_cli(lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self	)		->				Optional[int]:
										_snake_case						=					{
										    'teacher': T5_TINY,
										    'student': T5_TINIER,
										    'model_name_or_path': T5_TINIER,
										    'tokenizer_name': T5_TINIER,
										}
										self._test_distiller_cli(lowerCAmelCase_	)






					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_=True	)		->				Tuple:
										_snake_case						=					{
										    'label_smoothing': 0.0,
										    'early_stopping_patience': -1,
										    'train_batch_size': 1,
										    'eval_batch_size': 2,
										    'max_epochs': 2,
										    'alpha_mlm': 0.2,
										    'alpha_ce': 0.8,
										    'do_predict': True,
										    'model_name_or_path': 'sshleifer/tinier_bart',
										    'teacher': CHEAP_ARGS['model_name_or_path'],
										    'val_check_interval': 0.5,
										}
										default_updates.update(lowerCAmelCase_	)
										_snake_case						=					CHEAP_ARGS.copy()
										_snake_case						=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()	)
										_snake_case						=					self.get_auto_remove_tmp_dir()

										args_d.update(data_dir=lowerCAmelCase_					,    output_dir=lowerCAmelCase_					,    **lowerCAmelCase_	)
										_snake_case						=					distill_main(argparse.Namespace(**lowerCAmelCase_	)	)
										if not check_contents:
															return model
										_snake_case						=					os.listdir(lowerCAmelCase_	)
										_snake_case						=					{os.path.basename(lowerCAmelCase_	) for p in contents}
										_snake_case						=					[p for p in contents if p.endswith('ckpt'	)]
										assert len(lowerCAmelCase_	) > 0

										self.assertIn('test_generations.txt'					,    lowerCAmelCase_	)
										self.assertIn('test_results.txt'					,    lowerCAmelCase_	)

										_snake_case						=					load_json(model.metrics_save_path	)
										_snake_case						=					metrics['val'][-1]
										self.assertGreaterEqual(last_step_stats['val_avg_gen_time']					,    0.01	)
										self.assertGreaterEqual(1.0					,    last_step_stats['val_avg_gen_time']	)
										self.assertIsInstance(last_step_stats[F'''val_avg_{model.val_metric}''']					,    lowerCAmelCase_	)
										_snake_case						=					int(args_d['max_epochs'] * (1 / args_d['val_check_interval']) + 1	)
										self.assertEqual(len(metrics['val']	)					,    lowerCAmelCase_	)
										self.assertEqual(len(metrics['test']	)					,    1	)
										return model





class       UpperCamelCase_		(	_lowerCamelCase       ):




					@parameterized.expand(
					    [T5_TINY, BART_TINY, MBART_TINY, MARIAN_TINY, FSMT_TINY]					,    )
					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_	)		->				Optional[Any]:
										_snake_case						=					CHEAP_ARGS.copy()
										_snake_case						=					'translation' if model in [MBART_TINY, MARIAN_TINY, FSMT_TINY] else 'summarization'
										_snake_case						=					0.1 if task == 'translation' else 0

										_snake_case						=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()	)
										_snake_case						=					self.get_auto_remove_tmp_dir()
										args_d.update(
										    data_dir=lowerCAmelCase_					,    model_name_or_path=lowerCAmelCase_					,    tokenizer_name=lowerCAmelCase_					,    train_batch_size=2					,    eval_batch_size=2					,    output_dir=lowerCAmelCase_					,    do_predict=lowerCAmelCase_					,    task=lowerCAmelCase_					,    src_lang='en_XX'					,    tgt_lang='ro_RO'					,    freeze_encoder=lowerCAmelCase_					,    freeze_embeds=lowerCAmelCase_					,    )
										assert "n_train" in args_d
										_snake_case						=					argparse.Namespace(**lowerCAmelCase_	)
										_snake_case						=					main(lowerCAmelCase_	)

										_snake_case						=					module.model.get_input_embeddings()
										assert not input_embeds.weight.requires_grad
										if model == T5_TINY:
															_snake_case						=					module.model.lm_head
															assert not lm_head.weight.requires_grad
															assert (lm_head.weight == input_embeds.weight).all().item()
										elif model == FSMT_TINY:
															_snake_case						=					module.model.model
															_snake_case						=					fsmt.decoder.embed_positions
															assert not embed_pos.weight.requires_grad
															assert not fsmt.decoder.embed_tokens.weight.requires_grad
															# check that embeds are not the same
															assert fsmt.decoder.embed_tokens != fsmt.encoder.embed_tokens
										else:
															_snake_case						=					module.model.model
															_snake_case						=					bart.decoder.embed_positions
															assert not embed_pos.weight.requires_grad
															assert not bart.shared.weight.requires_grad
															# check that embeds are the same
															assert bart.decoder.embed_tokens == bart.encoder.embed_tokens
															assert bart.decoder.embed_tokens == bart.shared

										_snake_case						=					load_json(module.output_dir / 'text_batch.json'	)
										assert isinstance(lowerCAmelCase_					,    lowerCAmelCase_	)
										assert len(lowerCAmelCase_	) >= 4




					def 						lowerCAmelCase      (		self	)		->				str:
										_snake_case						=					CHEAP_ARGS.copy()

										_snake_case						=					'summarization'
										_snake_case						=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()	)

										args_d.update(
										    data_dir=lowerCAmelCase_					,    tokenizer_name=lowerCAmelCase_					,    train_batch_size=2					,    eval_batch_size=2					,    do_predict=lowerCAmelCase_					,    task=lowerCAmelCase_					,    src_lang='en_XX'					,    tgt_lang='ro_RO'					,    freeze_encoder=lowerCAmelCase_					,    freeze_embeds=lowerCAmelCase_					,    )

										# test models whose config includes the extra_model_args
										_snake_case						=					BART_TINY
										_snake_case						=					self.get_auto_remove_tmp_dir()
										_snake_case						=					args_d.copy()
										args_da.update(
										    model_name_or_path=lowerCAmelCase_					,    output_dir=lowerCAmelCase_					,    )
										_snake_case						=					('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout')
										for p in extra_model_params:
															_snake_case						=					0.5
										_snake_case						=					argparse.Namespace(**lowerCAmelCase_	)
										_snake_case						=					main(lowerCAmelCase_	)
										for p in extra_model_params:
															assert getattr(model.config					,    lowerCAmelCase_	) == 0.5, F'''failed to override the model config for param {p}'''

										# test models whose config doesn't include the extra_model_args
										_snake_case						=					T5_TINY
										_snake_case						=					self.get_auto_remove_tmp_dir()
										_snake_case						=					args_d.copy()
										args_da.update(
										    model_name_or_path=lowerCAmelCase_					,    output_dir=lowerCAmelCase_					,    )
										_snake_case						=					'encoder_layerdrop'
										_snake_case						=					0.5
										_snake_case						=					argparse.Namespace(**lowerCAmelCase_	)
										with pytest.raises(lowerCAmelCase_	) as excinfo:
															_snake_case						=					main(lowerCAmelCase_	)
										assert str(excinfo.value	) == F'''model config doesn\'t have a `{unsupported_param}` attribute'''






					def 						lowerCAmelCase      (		self	)		->				Tuple:
										_snake_case						=					CHEAP_ARGS.copy()

										_snake_case						=					'summarization'
										_snake_case						=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()	)

										_snake_case						=					BART_TINY
										_snake_case						=					self.get_auto_remove_tmp_dir()

										args_d.update(
										    data_dir=lowerCAmelCase_					,    model_name_or_path=lowerCAmelCase_					,    output_dir=lowerCAmelCase_					,    tokenizer_name=lowerCAmelCase_					,    train_batch_size=2					,    eval_batch_size=2					,    do_predict=lowerCAmelCase_					,    task=lowerCAmelCase_					,    src_lang='en_XX'					,    tgt_lang='ro_RO'					,    freeze_encoder=lowerCAmelCase_					,    freeze_embeds=lowerCAmelCase_					,    )

										# emulate finetune.py
										_snake_case						=					argparse.ArgumentParser()
										_snake_case						=					pl.Trainer.add_argparse_args(lowerCAmelCase_	)
										_snake_case						=					SummarizationModule.add_model_specific_args(lowerCAmelCase_					,    os.getcwd()	)
										_snake_case						=					{'--help': True}

										# --help test
										with pytest.raises(lowerCAmelCase_	) as excinfo:
															with CaptureStdout() as cs:
																				_snake_case						=					parser.parse_args(lowerCAmelCase_	)
															assert False, "--help is expected to sys.exit"
										assert excinfo.type == SystemExit
										_snake_case						=					lightning_base.arg_to_scheduler_metavar
										assert expected in cs.out, "--help is expected to list the supported schedulers"

										# --lr_scheduler=non_existing_scheduler test
										_snake_case						=					'non_existing_scheduler'
										_snake_case						=					{F'''--lr_scheduler={unsupported_param}'''}
										with pytest.raises(lowerCAmelCase_	) as excinfo:
															with CaptureStderr() as cs:
																				_snake_case						=					parser.parse_args(lowerCAmelCase_	)
															assert False, "invalid argument is expected to sys.exit"
										assert excinfo.type == SystemExit
										_snake_case						=					F'''invalid choice: \'{unsupported_param}\''''
										assert expected in cs.err, F'''should have bailed on invalid choice of scheduler {unsupported_param}'''

										# --lr_scheduler=existing_scheduler test
										_snake_case						=					'cosine'
										_snake_case						=					args_d.copy()
										_snake_case						=					supported_param
										_snake_case						=					argparse.Namespace(**lowerCAmelCase_	)
										_snake_case						=					main(lowerCAmelCase_	)
										assert (
										    getattr(model.hparams					,    'lr_scheduler'	) == supported_param
										), F'''lr_scheduler={supported_param} shouldn\'t fail'''










# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


UpperCAmelCase_   				=  os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
UpperCAmelCase_   				=  os.path.join(hf_cache_home, """accelerate""")
UpperCAmelCase_   				=  os.path.join(cache_dir, """default_config.yaml""")
UpperCAmelCase_   				=  os.path.join(cache_dir, """default_config.yaml""")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
					UpperCAmelCase_   				=  default_yaml_config_file
else:
					UpperCAmelCase_   				=  default_json_config_file





def     lowerCamelCase__  (  UpperCamelCase__      :							List[str]    )      ->			str:



					'''simple docstring'''




					if config_file is not None:
										if not os.path.isfile(UpperCamelCase__    ):
															raise FileNotFoundError(
															    F'''The passed configuration file `{config_file}` does not exist. '''
															    'Please pass an existing file to `accelerate launch`, or use the the default one '
															    'created through `accelerate config` and run `accelerate launch` '
															    'without the `--config_file` argument.'    )
					else:
										_snake_case						=					default_config_file
					with open(UpperCamelCase__							,     'r'							,     encoding='utf-8'    ) as f:
										if config_file.endswith('.json'    ):
															if (
															    json.load(UpperCamelCase__    ).get('compute_environment'							,     ComputeEnvironment.LOCAL_MACHINE    )
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				_snake_case						=					ClusterConfig
															else:
																				_snake_case						=					SageMakerConfig
															return config_class.from_json_file(json_file=UpperCamelCase__    )
										else:
															if (
															    yaml.safe_load(UpperCamelCase__    ).get('compute_environment'							,     ComputeEnvironment.LOCAL_MACHINE    )
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				_snake_case						=					ClusterConfig
															else:
																				_snake_case						=					SageMakerConfig
															return config_class.from_yaml_file(yaml_file=UpperCamelCase__    )
@dataclass
class       UpperCamelCase_		:
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42




					def 						lowerCAmelCase      (		self	)		->				Optional[Any]:
										_snake_case						=					self.__dict__
										# For serialization, it's best to convert Enums to strings (or their underlying value type).
										for key, value in result.items():
															if isinstance(lowerCAmelCase_					,    lowerCAmelCase_	):
																				_snake_case						=					value.value
															if isinstance(lowerCAmelCase_					,    lowerCAmelCase_	) and not bool(lowerCAmelCase_	):
																				_snake_case						=					None
										_snake_case						=					{k: v for k, v in result.items() if v is not None}
										return result




					@classmethod
					def 						lowerCAmelCase      (		cls					,    lowerCAmelCase_=None	)		->				List[Any]:
										_snake_case						=					default_json_config_file if json_file is None else json_file
										with open(lowerCAmelCase_					,    'r'					,    encoding='utf-8'	) as f:
															_snake_case						=					json.load(lowerCAmelCase_	)
										if "compute_environment" not in config_dict:
															_snake_case						=					ComputeEnvironment.LOCAL_MACHINE
										if "mixed_precision" not in config_dict:
															_snake_case						=					'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_snake_case						=					config_dict.pop('dynamo_backend'	)
															_snake_case						=					{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
															_snake_case						=					False
										return cls(**lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_	)		->				List[str]:
										with open(lowerCAmelCase_					,    'w'					,    encoding='utf-8'	) as f:
															_snake_case						=					json.dumps(self.to_dict()					,    indent=2					,    sort_keys=lowerCAmelCase_	) + '\n'
															f.write(lowerCAmelCase_	)




					@classmethod
					def 						lowerCAmelCase      (		cls					,    lowerCAmelCase_=None	)		->				int:
										_snake_case						=					default_yaml_config_file if yaml_file is None else yaml_file
										with open(lowerCAmelCase_					,    'r'					,    encoding='utf-8'	) as f:
															_snake_case						=					yaml.safe_load(lowerCAmelCase_	)
										if "compute_environment" not in config_dict:
															_snake_case						=					ComputeEnvironment.LOCAL_MACHINE

										if "mixed_precision" not in config_dict:
															_snake_case						=					'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if isinstance(config_dict['mixed_precision']					,    lowerCAmelCase_	) and not config_dict["mixed_precision"]:
															_snake_case						=					'no'
										if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_snake_case						=					config_dict.pop('dynamo_backend'	)
															_snake_case						=					{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
															_snake_case						=					False
										return cls(**lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_	)		->				List[str]:
										with open(lowerCAmelCase_					,    'w'					,    encoding='utf-8'	) as f:
															yaml.safe_dump(self.to_dict()					,    lowerCAmelCase_	)






					def 						lowerCAmelCase      (		self	)		->				Tuple:
										if isinstance(self.compute_environment					,    lowerCAmelCase_	):
															_snake_case						=					ComputeEnvironment(self.compute_environment	)
										if isinstance(self.distributed_type					,    lowerCAmelCase_	):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																				_snake_case						=					SageMakerDistributedType(self.distributed_type	)
															else:
																				_snake_case						=					DistributedType(self.distributed_type	)
										if self.dynamo_config is None:
															_snake_case						=					{}





@dataclass
class       UpperCamelCase_		(	_lowerCamelCase       ):
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						0
					lowerCAmelCase_				=						1
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						"static"
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						"main"

					# args for deepspeed_plugin
					lowerCAmelCase_				=						None
					# args for fsdp
					lowerCAmelCase_				=						None
					# args for megatron_lm
					lowerCAmelCase_				=						None
					# args for ipex
					lowerCAmelCase_				=						None
					# args for TPU
					lowerCAmelCase_				=						False

					# args for TPU pods
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None

					# args for dynamo
					lowerCAmelCase_				=						None




					def 						lowerCAmelCase      (		self	)		->				Optional[Any]:
										if self.deepspeed_config is None:
															_snake_case						=					{}
										if self.fsdp_config is None:
															_snake_case						=					{}
										if self.megatron_lm_config is None:
															_snake_case						=					{}
										if self.ipex_config is None:
															_snake_case						=					{}
										return super().__post_init__()





@dataclass
class       UpperCamelCase_		(	_lowerCamelCase       ):
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						"us-east-1"
					lowerCAmelCase_				=						1
					lowerCAmelCase_				=						"all"
					lowerCAmelCase_				=						f"accelerate-sagemaker-{num_machines}"
					lowerCAmelCase_				=						SAGEMAKER_PYTORCH_VERSION
					lowerCAmelCase_				=						SAGEMAKER_TRANSFORMERS_VERSION
					lowerCAmelCase_				=						SAGEMAKER_PYTHON_VERSION
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None



