

import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCamelCase__	:   str								=     logging.getLogger(__name__)


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		int							):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_						=    p * torch.log(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    0
    return -plogp.sum(dim=-1							)


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		Any							):





    """simple docstring"""


    logger.info('lv, h >\t' + '\t'.join(f"""{x + 1}""" for x in range(len(lowercase__							)							)							)							)
    for row in range(len(lowercase__							)							):
        if tensor.dtype != torch.long:
            logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:.5f}""" for x in tensor[row].cpu().data							)							)
        else:
            logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:d}""" for x in tensor[row].cpu().data							)							)


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		List[Any]			, _SCREAMING_SNAKE_CASE       :		Dict			, _SCREAMING_SNAKE_CASE       :		int			, _SCREAMING_SNAKE_CASE       :		Union[str, Any]=True			, _SCREAMING_SNAKE_CASE       :		Optional[int]=True			, _SCREAMING_SNAKE_CASE       :		Dict=None			, _SCREAMING_SNAKE_CASE       :		Optional[int]=False							):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    model.config.num_hidden_layers, model.config.num_attention_heads
    SCREAMING_SNAKE_CASE_						=    torch.zeros(lowercase__			, lowercase__							).to(args.device							)
    SCREAMING_SNAKE_CASE_						=    torch.zeros(lowercase__			, lowercase__							).to(args.device							)

    if head_mask is None:
        SCREAMING_SNAKE_CASE_						=    torch.ones(lowercase__			, lowercase__							).to(args.device							)

    head_mask.requires_grad_(requires_grad=lowercase__							)
    # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
    if actually_pruned:
        SCREAMING_SNAKE_CASE_						=    None

    SCREAMING_SNAKE_CASE_						=    None
    SCREAMING_SNAKE_CASE_						=    None
    SCREAMING_SNAKE_CASE_						=    0.0

    for step, inputs in enumerate(tqdm(lowercase__			, desc='Iteration'			, disable=args.local_rank not in [-1, 0]							)							):
        for k, v in inputs.items():
            SCREAMING_SNAKE_CASE_						=    v.to(args.device							)

        # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
        SCREAMING_SNAKE_CASE_						=    model(**lowercase__			, head_mask=lowercase__							)
        SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    (
            outputs[0],
            outputs[1],
            outputs[-1],
        )  # Loss and logits are the first, attention the last
        loss.backward()  # Backpropagate to populate the gradients in the head mask

        if compute_entropy:
            for layer, attn in enumerate(lowercase__							):
                SCREAMING_SNAKE_CASE_						=    entropy(attn.detach()							) * inputs['attention_mask'].float().unsqueeze(1							)
                attn_entropy[layer] += masked_entropy.sum(-1							).sum(0							).detach()

        if compute_importance:
            head_importance += head_mask.grad.abs().detach()

        # Also store our logits/labels if we want to compute metrics afterwards
        if preds is None:
            SCREAMING_SNAKE_CASE_						=    logits.detach().cpu().numpy()
            SCREAMING_SNAKE_CASE_						=    inputs['labels'].detach().cpu().numpy()
        else:
            SCREAMING_SNAKE_CASE_						=    np.append(lowercase__			, logits.detach().cpu().numpy()			, axis=0							)
            SCREAMING_SNAKE_CASE_						=    np.append(lowercase__			, inputs['labels'].detach().cpu().numpy()			, axis=0							)

        tot_tokens += inputs["attention_mask"].float().detach().sum().data

    # Normalize
    attn_entropy /= tot_tokens
    head_importance /= tot_tokens
    # Layerwise importance normalization
    if not args.dont_normalize_importance_by_layer:
        SCREAMING_SNAKE_CASE_						=    2
        SCREAMING_SNAKE_CASE_						=    torch.pow(torch.pow(lowercase__			, lowercase__							).sum(-1							)			, 1 / exponent							)
        head_importance /= norm_by_layer.unsqueeze(-1							) + 1E-2_0

    if not args.dont_normalize_global_importance:
        SCREAMING_SNAKE_CASE_						=    (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

    # Print/save matrices
    np.save(os.path.join(args.output_dir			, 'attn_entropy.npy'							)			, attn_entropy.detach().cpu().numpy()							)
    np.save(os.path.join(args.output_dir			, 'head_importance.npy'							)			, head_importance.detach().cpu().numpy()							)

    logger.info('Attention entropies'							)
    print_ad_tensor(lowercase__							)
    logger.info('Head importance scores'							)
    print_ad_tensor(lowercase__							)
    logger.info('Head ranked by importance scores'							)
    SCREAMING_SNAKE_CASE_						=    torch.zeros(head_importance.numel()			, dtype=torch.long			, device=args.device							)
    SCREAMING_SNAKE_CASE_						=    torch.arange(
        head_importance.numel()			, device=args.device							)
    SCREAMING_SNAKE_CASE_						=    head_ranks.view_as(lowercase__							)
    print_ad_tensor(lowercase__							)

    return attn_entropy, head_importance, preds, labels


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		Optional[Any]			, _SCREAMING_SNAKE_CASE       :		int			, _SCREAMING_SNAKE_CASE       :		str							):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    compute_heads_importance(lowercase__			, lowercase__			, lowercase__			, compute_entropy=lowercase__							)
    SCREAMING_SNAKE_CASE_						=    np.argmax(lowercase__			, axis=1							) if args.output_mode == 'classification' else np.squeeze(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    glue_compute_metrics(args.task_name			, lowercase__			, lowercase__							)[args.metric_name]
    logger.info('Pruning: original score: %f, threshold: %f'			, lowercase__			, original_score * args.masking_threshold							)

    SCREAMING_SNAKE_CASE_						=    torch.ones_like(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    max(1			, int(new_head_mask.numel() * args.masking_amount							)							)

    SCREAMING_SNAKE_CASE_						=    original_score
    while current_score >= original_score * args.masking_threshold:
        SCREAMING_SNAKE_CASE_						=    new_head_mask.clone()  # save current head mask
        # heads from least important to most - keep only not-masked heads
        SCREAMING_SNAKE_CASE_						=    float('Inf'							)
        SCREAMING_SNAKE_CASE_						=    head_importance.view(-1							).sort()[1]

        if len(lowercase__							) <= num_to_mask:
            break

        # mask heads
        SCREAMING_SNAKE_CASE_						=    current_heads_to_mask[:num_to_mask]
        logger.info('Heads to mask: %s'			, str(current_heads_to_mask.tolist()							)							)
        SCREAMING_SNAKE_CASE_						=    new_head_mask.view(-1							)
        SCREAMING_SNAKE_CASE_						=    0.0
        SCREAMING_SNAKE_CASE_						=    new_head_mask.view_as(lowercase__							)
        SCREAMING_SNAKE_CASE_						=    new_head_mask.clone().detach()
        print_ad_tensor(lowercase__							)

        # Compute metric and head importance again
        SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    compute_heads_importance(
            lowercase__			, lowercase__			, lowercase__			, compute_entropy=lowercase__			, head_mask=lowercase__							)
        SCREAMING_SNAKE_CASE_						=    np.argmax(lowercase__			, axis=1							) if args.output_mode == 'classification' else np.squeeze(lowercase__							)
        SCREAMING_SNAKE_CASE_						=    glue_compute_metrics(args.task_name			, lowercase__			, lowercase__							)[args.metric_name]
        logger.info(
            'Masking: current score: %f, remaining heads %d (%.1f percents)'			, lowercase__			, new_head_mask.sum()			, new_head_mask.sum() / new_head_mask.numel() * 100			, )

    logger.info('Final head mask'							)
    print_ad_tensor(lowercase__							)
    np.save(os.path.join(args.output_dir			, 'head_mask.npy'							)			, head_mask.detach().cpu().numpy()							)

    return head_mask


def        _UpperCAmelCase							(	_SCREAMING_SNAKE_CASE       :		Dict			, _SCREAMING_SNAKE_CASE       :		List[str]			, _SCREAMING_SNAKE_CASE       :		str			, _SCREAMING_SNAKE_CASE       :		Dict							):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_						=    datetime.now()
    SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    compute_heads_importance(
        lowercase__			, lowercase__			, lowercase__			, compute_entropy=lowercase__			, compute_importance=lowercase__			, head_mask=lowercase__							)
    SCREAMING_SNAKE_CASE_						=    np.argmax(lowercase__			, axis=1							) if args.output_mode == 'classification' else np.squeeze(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    glue_compute_metrics(args.task_name			, lowercase__			, lowercase__							)[args.metric_name]
    SCREAMING_SNAKE_CASE_						=    datetime.now() - before_time

    SCREAMING_SNAKE_CASE_						=    sum(p.numel() for p in model.parameters()							)
    SCREAMING_SNAKE_CASE_						=    {
        layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowercase__							)							)
    }

    assert sum(len(lowercase__							) for h in heads_to_prune.values()							) == (1 - head_mask.long()).sum().item()
    model.prune_heads(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    sum(p.numel() for p in model.parameters()							)

    SCREAMING_SNAKE_CASE_						=    datetime.now()
    SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    compute_heads_importance(
        lowercase__			, lowercase__			, lowercase__			, compute_entropy=lowercase__			, compute_importance=lowercase__			, head_mask=lowercase__			, actually_pruned=lowercase__			, )
    SCREAMING_SNAKE_CASE_						=    np.argmax(lowercase__			, axis=1							) if args.output_mode == 'classification' else np.squeeze(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    glue_compute_metrics(args.task_name			, lowercase__			, lowercase__							)[args.metric_name]
    SCREAMING_SNAKE_CASE_						=    datetime.now() - before_time

    logger.info(
        'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'			, lowercase__			, lowercase__			, pruned_num_params / original_num_params * 100			, )
    logger.info('Pruning: score with masking: %f score with pruning: %f'			, lowercase__			, lowercase__							)
    logger.info('Pruning: speed ratio (new timing / original timing): %f percents'			, original_time / new_time * 100							)


def        _UpperCAmelCase							(	):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_						=    argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        '--data_dir'			, default=lowercase__			, type=lowercase__			, required=lowercase__			, help='The input data dir. Should contain the .tsv files (or other data files) for the task.'			, )
    parser.add_argument(
        '--model_name_or_path'			, default=lowercase__			, type=lowercase__			, required=lowercase__			, help='Path to pretrained model or model identifier from huggingface.co/models'			, )
    parser.add_argument(
        '--task_name'			, default=lowercase__			, type=lowercase__			, required=lowercase__			, help='The name of the task to train selected in the list: ' + ', '.join(glue_processors.keys()							)			, )
    parser.add_argument(
        '--output_dir'			, default=lowercase__			, type=lowercase__			, required=lowercase__			, help='The output directory where the model predictions and checkpoints will be written.'			, )

    # Other parameters
    parser.add_argument(
        '--config_name'			, default=''			, type=lowercase__			, help='Pretrained config name or path if not the same as model_name_or_path'			, )
    parser.add_argument(
        '--tokenizer_name'			, default=''			, type=lowercase__			, help='Pretrained tokenizer name or path if not the same as model_name_or_path'			, )
    parser.add_argument(
        '--cache_dir'			, default=lowercase__			, type=lowercase__			, help='Where do you want to store the pre-trained models downloaded from huggingface.co'			, )
    parser.add_argument(
        '--data_subset'			, type=lowercase__			, default=-1			, help='If > 0: limit the data to a subset of data_subset instances.'							)
    parser.add_argument(
        '--overwrite_output_dir'			, action='store_true'			, help='Whether to overwrite data in output directory'							)
    parser.add_argument(
        '--overwrite_cache'			, action='store_true'			, help='Overwrite the cached training and evaluation sets'							)

    parser.add_argument(
        '--dont_normalize_importance_by_layer'			, action='store_true'			, help='Don\'t normalize importance score by layers'							)
    parser.add_argument(
        '--dont_normalize_global_importance'			, action='store_true'			, help='Don\'t normalize all importance scores between 0 and 1'			, )

    parser.add_argument(
        '--try_masking'			, action='store_true'			, help='Whether to try to mask head until a threshold of accuracy.'							)
    parser.add_argument(
        '--masking_threshold'			, default=0.9			, type=lowercase__			, help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'			, )
    parser.add_argument(
        '--masking_amount'			, default=0.1			, type=lowercase__			, help='Amount to heads to masking at each masking step.'							)
    parser.add_argument('--metric_name'			, default='acc'			, type=lowercase__			, help='Metric to use for head masking.'							)

    parser.add_argument(
        '--max_seq_length'			, default=128			, type=lowercase__			, help=(
            'The maximum total input sequence length after WordPiece tokenization. \n'
            'Sequences longer than this will be truncated, sequences shorter padded.'
        )			, )
    parser.add_argument('--batch_size'			, default=1			, type=lowercase__			, help='Batch size.'							)

    parser.add_argument('--seed'			, type=lowercase__			, default=42							)
    parser.add_argument('--local_rank'			, type=lowercase__			, default=-1			, help='local_rank for distributed training on gpus'							)
    parser.add_argument('--no_cuda'			, action='store_true'			, help='Whether not to use CUDA when available'							)
    parser.add_argument('--server_ip'			, type=lowercase__			, default=''			, help='Can be used for distant debugging.'							)
    parser.add_argument('--server_port'			, type=lowercase__			, default=''			, help='Can be used for distant debugging.'							)
    SCREAMING_SNAKE_CASE_						=    parser.parse_args()

    if args.server_ip and args.server_port:
        # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
        import ptvsd

        print('Waiting for debugger attach'							)
        ptvsd.enable_attach(address=(args.server_ip, args.server_port)			, redirect_output=lowercase__							)
        ptvsd.wait_for_attach()

    # Setup devices and distributed training
    if args.local_rank == -1 or args.no_cuda:
        SCREAMING_SNAKE_CASE_						=    torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'							)
        SCREAMING_SNAKE_CASE_						=    0 if args.no_cuda else torch.cuda.device_count()
    else:
        torch.cuda.set_device(args.local_rank							)
        SCREAMING_SNAKE_CASE_						=    torch.device('cuda'			, args.local_rank							)
        SCREAMING_SNAKE_CASE_						=    1
        torch.distributed.init_process_group(backend='nccl'							)  # Initializes the distributed backend

    # Setup logging
    logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN							)
    logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device			, args.n_gpu			, bool(args.local_rank != -1							)							)							)
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(args.local_rank							):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()

    # Set seeds
    set_seed(args.seed							)

    # Prepare GLUE task
    SCREAMING_SNAKE_CASE_						=    args.task_name.lower()
    if args.task_name not in glue_processors:
        raise ValueError('Task not found: %s' % (args.task_name)							)
    SCREAMING_SNAKE_CASE_						=    glue_processors[args.task_name]()
    SCREAMING_SNAKE_CASE_						=    glue_output_modes[args.task_name]
    SCREAMING_SNAKE_CASE_						=    processor.get_labels()
    SCREAMING_SNAKE_CASE_						=    len(lowercase__							)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    SCREAMING_SNAKE_CASE_						=    AutoConfig.from_pretrained(
        args.config_name if args.config_name else args.model_name_or_path			, num_labels=lowercase__			, finetuning_task=args.task_name			, output_attentions=lowercase__			, cache_dir=args.cache_dir			, )
    SCREAMING_SNAKE_CASE_						=    AutoTokenizer.from_pretrained(
        args.tokenizer_name if args.tokenizer_name else args.model_name_or_path			, cache_dir=args.cache_dir			, )
    SCREAMING_SNAKE_CASE_						=    AutoModelForSequenceClassification.from_pretrained(
        args.model_name_or_path			, from_tf=bool('.ckpt' in args.model_name_or_path							)			, config=lowercase__			, cache_dir=args.cache_dir			, )

    # Distributed and parallel training
    model.to(args.device							)
    if args.local_rank != -1:
        SCREAMING_SNAKE_CASE_						=    nn.parallel.DistributedDataParallel(
            lowercase__			, device_ids=[args.local_rank]			, output_device=args.local_rank			, find_unused_parameters=lowercase__							)
    elif args.n_gpu > 1:
        SCREAMING_SNAKE_CASE_						=    nn.DataParallel(lowercase__							)

    # Print/save training arguments
    os.makedirs(args.output_dir			, exist_ok=lowercase__							)
    torch.save(lowercase__			, os.path.join(args.output_dir			, 'run_args.bin'							)							)
    logger.info('Training/evaluation parameters %s'			, lowercase__							)

    # Prepare dataset for the GLUE task
    SCREAMING_SNAKE_CASE_						=    GlueDataset(lowercase__			, tokenizer=lowercase__			, mode='dev'							)
    if args.data_subset > 0:
        SCREAMING_SNAKE_CASE_						=    Subset(lowercase__			, list(range(min(args.data_subset			, len(lowercase__							)							)							)							)							)
    SCREAMING_SNAKE_CASE_						=    SequentialSampler(lowercase__							) if args.local_rank == -1 else DistributedSampler(lowercase__							)
    SCREAMING_SNAKE_CASE_						=    DataLoader(
        lowercase__			, sampler=lowercase__			, batch_size=args.batch_size			, collate_fn=lowercase__							)

    # Compute head entropy and importance score
    compute_heads_importance(lowercase__			, lowercase__			, lowercase__							)

    # Try head masking (set heads to zero until the score goes under a threshole)
    # and head pruning (remove masked heads and see the effect on the network)
    if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
        SCREAMING_SNAKE_CASE_						=    mask_heads(lowercase__			, lowercase__			, lowercase__							)
        prune_heads(lowercase__			, lowercase__			, lowercase__			, lowercase__							)


if __name__ == "__main__":
       main()







# 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 			UpperCAmelCase__     (     lowercase__ )			->   int:
						if config_file is not None:
												if not os.path.isfile(lowercase__ ):
																		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:
												__lowercase											=					default_config_file
						with open(lowercase__    ,							"""r"""    ,							encoding="""utf-8""" ) as f:
												if config_file.endswith(""".json""" ):
																		if (
																		    json.load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_json_file(json_file=lowercase__ )
												else:
																		if (
																		    yaml.safe_load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=lowercase__ )
@dataclass
class       _lowerCAmelCase :






			"""simple docstring"""





			lowercase__   :	ComputeEnvironment
			lowercase__   :	Union[DistributedType, SageMakerDistributedType]
			lowercase__   :	str
			lowercase__   :	bool





			def 		snake_case__      (					self						:							Union[str, Any] )    ->       List[Any]:
									"""simple docstring"""







									__lowercase											=					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(lowercase      ,  lowercase ):
																					__lowercase											=					value.value
															if isinstance(lowercase      ,  lowercase ) and not bool(lowercase ):
																					__lowercase											=					None
									__lowercase											=					{k: v for k, v in result.items() if v is not None}
									return result





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							List[str]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_json_config_file if json_file is None else json_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							str )    ->       Any:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.dumps(self.to_dict()      ,  indent=2      ,  sort_keys=lowercase ) + """\n"""
															f.write(lowercase )





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							Optional[Any]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					yaml.safe_load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if isinstance(config_dict["""mixed_precision"""]      ,  lowercase ) and not config_dict["mixed_precision"]:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Union[str, Any]      ,  lowercase						:							Any )    ->       Tuple:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															yaml.safe_dump(self.to_dict()      ,  lowercase )







			def 		snake_case__      (					self						:							int )    ->       Optional[int]:
									"""simple docstring"""







									if isinstance(self.compute_environment      ,  lowercase ):
															__lowercase											=					ComputeEnvironment(self.compute_environment )
									if isinstance(self.distributed_type      ,  lowercase ):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					__lowercase											=					SageMakerDistributedType(self.distributed_type )
															else:
																					__lowercase											=					DistributedType(self.distributed_type )
									if self.dynamo_config is None:
															__lowercase											=					{}





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	int
			lowercase__   :	int  			=      0
			lowercase__   :	int  			=      1
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[int]  			=      None
			lowercase__   :	Optional[str]  			=      "static"
			lowercase__   :	Optional[bool]  			=      False
			lowercase__   :	str  			=      "main"

			# args for deepspeed_plugin
			lowercase__   :	dict  			=      None
			# args for fsdp
			lowercase__   :	dict  			=      None
			# args for megatron_lm
			lowercase__   :	dict  			=      None
			# args for ipex
			lowercase__   :	dict  			=      None
			# args for TPU
			lowercase__   :	bool  			=      False

			# args for TPU pods
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	bool  			=      False
			lowercase__   :	bool  			=      False
			lowercase__   :	str  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None

			# args for dynamo
			lowercase__   :	dict  			=      None





			def 		snake_case__      (					self						:							List[Any] )    ->       int:
									"""simple docstring"""







									if self.deepspeed_config is None:
															__lowercase											=					{}
									if self.fsdp_config is None:
															__lowercase											=					{}
									if self.megatron_lm_config is None:
															__lowercase											=					{}
									if self.ipex_config is None:
															__lowercase											=					{}
									return super().__post_init__()





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	str
			lowercase__   :	str
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	str  			=      "us-east-1"
			lowercase__   :	int  			=      1
			lowercase__   :	str  			=      "all"
			lowercase__   :	str  			=      F'''accelerate-sagemaker-{num_machines}'''
			lowercase__   :	str  			=      SAGEMAKER_PYTORCH_VERSION
			lowercase__   :	str  			=      SAGEMAKER_TRANSFORMERS_VERSION
			lowercase__   :	str  			=      SAGEMAKER_PYTHON_VERSION
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	dict  			=      None
			lowercase__   :	dict  			=      None





