
"""simple docstring"""




from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.swin.modeling_tf_swin import (
        TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFSwinForImageClassification,
        TFSwinForMaskedImageModeling,
        TFSwinModel,
    )


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor







class 						lowercase:



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE=1_3    ,							__SCREAMING_SNAKE_CASE=3_2    ,							__SCREAMING_SNAKE_CASE=2    ,							__SCREAMING_SNAKE_CASE=3    ,							__SCREAMING_SNAKE_CASE=1_6    ,							__SCREAMING_SNAKE_CASE=[1, 2, 1]    ,							__SCREAMING_SNAKE_CASE=[2, 2, 4]    ,							__SCREAMING_SNAKE_CASE=2    ,							__SCREAMING_SNAKE_CASE=2.0    ,							__SCREAMING_SNAKE_CASE=True    ,							__SCREAMING_SNAKE_CASE=0.0    ,							__SCREAMING_SNAKE_CASE=0.0    ,							__SCREAMING_SNAKE_CASE=0.1    ,							__SCREAMING_SNAKE_CASE="gelu"    ,							__SCREAMING_SNAKE_CASE=False    ,							__SCREAMING_SNAKE_CASE=True    ,							__SCREAMING_SNAKE_CASE=0.02    ,							__SCREAMING_SNAKE_CASE=1e-5    ,							__SCREAMING_SNAKE_CASE=True    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=True    ,							__SCREAMING_SNAKE_CASE=1_0    ,							__SCREAMING_SNAKE_CASE=8    ,							)		->    None:







         """simple docstring"""



         a__    = parent
         a__    = batch_size
         a__    = image_size
         a__    = patch_size
         a__    = num_channels
         a__    = embed_dim
         a__    = depths
         a__    = num_heads
         a__    = window_size
         a__    = mlp_ratio
         a__    = qkv_bias
         a__    = hidden_dropout_prob
         a__    = attention_probs_dropout_prob
         a__    = drop_path_rate
         a__    = hidden_act
         a__    = use_absolute_embeddings
         a__    = patch_norm
         a__    = layer_norm_eps
         a__    = initializer_range
         a__    = is_training
         a__    = scope
         a__    = use_labels
         a__    = type_sequence_label_size
         a__    = encoder_stride



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         a__    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

         a__    = None
         if self.use_labels:
             a__    = ids_tensor([self.batch_size]    ,							self.type_sequence_label_size      )

         a__    = self.get_config()

         return config, pixel_values, labels



     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         return SwinConfig(
             image_size=self.image_size    ,							patch_size=self.patch_size    ,							num_channels=self.num_channels    ,							embed_dim=self.embed_dim    ,							depths=self.depths    ,							num_heads=self.num_heads    ,							window_size=self.window_size    ,							mlp_ratio=self.mlp_ratio    ,							qkv_bias=self.qkv_bias    ,							hidden_dropout_prob=self.hidden_dropout_prob    ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,							drop_path_rate=self.drop_path_rate    ,							hidden_act=self.hidden_act    ,							use_absolute_embeddings=self.use_absolute_embeddings    ,							path_norm=self.patch_norm    ,							layer_norm_eps=self.layer_norm_eps    ,							initializer_range=self.initializer_range    ,							encoder_stride=self.encoder_stride    ,							)



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    Dict:







         """simple docstring"""



         a__    = TFSwinModel(config=__SCREAMING_SNAKE_CASE      )
         a__    = model(__SCREAMING_SNAKE_CASE      )

         a__    = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
         a__    = int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

         self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, expected_seq_len, expected_dim)      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    List[str]:







         """simple docstring"""



         a__    = TFSwinForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE      )
         a__    = model(__SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(
             result.logits.shape    ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)      )

         # test greyscale images
         a__    = 1
         a__    = TFSwinForMaskedImageModeling(__SCREAMING_SNAKE_CASE      )

         a__    = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
         a__    = model(__SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, 1, self.image_size, self.image_size)      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    int:







         """simple docstring"""



         a__    = self.type_sequence_label_size
         a__    = TFSwinForImageClassification(__SCREAMING_SNAKE_CASE      )
         a__    = model(__SCREAMING_SNAKE_CASE    ,							labels=__SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.type_sequence_label_size)      )

         # test greyscale images
         a__    = 1
         a__    = TFSwinForImageClassification(__SCREAMING_SNAKE_CASE      )
         a__    = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
         a__    = model(__SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.type_sequence_label_size)      )




     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



         a__    = self.prepare_config_and_inputs()
         a__  ,    a__  ,    a__    = config_and_inputs
         a__    = {'pixel_values': pixel_values}
         return config, inputs_dict







@require_tf
class 						lowercase(_lowercase						,	_lowercase						,	unittest.TestCase					):
     __snake_case:  Any  				=    (
         (
             TFSwinModel,
             TFSwinForImageClassification,
             TFSwinForMaskedImageModeling,
         )
         if is_tf_available()
         else ()
     )
     __snake_case:  List[str]  				=    (
         {'feature-extraction': TFSwinModel, 'image-classification': TFSwinForImageClassification}
         if is_tf_available()
         else {}
     )

     __snake_case:  int  				=    False
     __snake_case:  Union[str, Any]  				=    False
     __snake_case:  Optional[int]  				=    False
     __snake_case:  str  				=    False



     def  lowercase__     (       self      )		->    Dict:







         """simple docstring"""



         a__    = TFSwinModelTester(self      )
         a__    = ConfigTester(self    ,							config_class=__SCREAMING_SNAKE_CASE    ,							embed_dim=3_7      )



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         return



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         a__    = self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self      )		->    Dict:







         """simple docstring"""



         a__    = self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE      )



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







         """simple docstring"""



         a__    = self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE      )



     @unittest.skip(reason='Swin does not use inputs_embeds'      )
     def  lowercase__     (       self      )		->    Dict:







         """simple docstring"""



         pass



     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         a__  ,    a__    = self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             a__    = model_class(__SCREAMING_SNAKE_CASE      )
             self.assertIsInstance(model.get_input_embeddings()    ,							tf.keras.layers.Layer      )
             a__    = model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE    ,							tf.keras.layers.Dense      )      )



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         a__  ,    a__    = self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             a__    = model_class(__SCREAMING_SNAKE_CASE      )
             a__    = inspect.signature(model.call      )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             a__    = [*signature.parameters.keys()]

             a__    = ['pixel_values']
             self.assertListEqual(arg_names[:1]    ,							__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         a__  ,    a__    = self.model_tester.prepare_config_and_inputs_for_common()
         a__    = True

         for model_class in self.all_model_classes:
             a__    = True
             a__    = False
             a__    = True
             a__    = model_class(__SCREAMING_SNAKE_CASE      )
             a__    = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )      )
             a__    = outputs.attentions
             a__    = len(self.model_tester.depths      )
             self.assertEqual(len(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE      )

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             a__    = True
             a__    = config.window_size**2
             a__    = model_class(__SCREAMING_SNAKE_CASE      )
             a__    = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )      )
             a__    = outputs.attentions
             self.assertEqual(len(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE      )

             self.assertListEqual(
                 list(attentions[0].shape[-3:]      )    ,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,							)
             a__    = len(__SCREAMING_SNAKE_CASE      )

             # Check attention is always last and order is fine
             a__    = True
             a__    = True
             a__    = model_class(__SCREAMING_SNAKE_CASE      )
             a__    = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )      )

             if hasattr(self.model_tester    ,							'num_hidden_states_types'      ):
                 a__    = self.model_tester.num_hidden_states_types
             else:
                 # also another +1 for reshaped_hidden_states
                 a__    = 2
             self.assertEqual(out_len + added_hidden_states    ,							len(__SCREAMING_SNAKE_CASE      )      )

             a__    = outputs.attentions

             self.assertEqual(len(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE      )

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]      )    ,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,							)



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    Optional[int]:







         """simple docstring"""



         a__    = model_class(__SCREAMING_SNAKE_CASE      )
         a__    = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )      )
         a__    = outputs.hidden_states

         a__    = getattr(
             self.model_tester    ,							'expected_num_hidden_layers'    ,							len(self.model_tester.depths      ) + 1      )
         self.assertEqual(len(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE      )

         # Swin has a different seq_length
         a__    = to_atuple(config.patch_size      )

         a__    = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

         self.assertListEqual(
             list(hidden_states[0].shape[-2:]      )    ,							[num_patches, self.model_tester.embed_dim]    ,							)

         a__    = outputs.reshaped_hidden_states
         self.assertEqual(len(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE      )

         a__  ,    a__  ,    a__  ,    a__    = reshaped_hidden_states[0].shape

         a__    = tf.reshape(reshaped_hidden_states[0]    ,							(batch_size, num_channels, height * width)      )
         a__    = tf.transpose(__SCREAMING_SNAKE_CASE    ,							(0, 2, 1)      )

         self.assertListEqual(
             list(reshaped_hidden_states.shape[-2:]      )    ,							[num_patches, self.model_tester.embed_dim]    ,							)



     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         a__  ,    a__    = self.model_tester.prepare_config_and_inputs_for_common()

         a__    = to_atuple(self.model_tester.image_size      )

         for model_class in self.all_model_classes:
             a__    = True
             self.check_hidden_states_output(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             a__    = True

             self.check_hidden_states_output(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self      )		->    List[Any]:







         """simple docstring"""



         a__  ,    a__    = self.model_tester.prepare_config_and_inputs_for_common()
         a__    = 3

         a__    = to_atuple(self.model_tester.image_size      )
         a__    = to_atuple(config.patch_size      )

         a__    = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         a__    = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
             a__    = True
             self.check_hidden_states_output(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							(padded_height, padded_width)      )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             a__    = True
             self.check_hidden_states_output(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							(padded_height, padded_width)      )




     @slow
     def  lowercase__     (       self      )		->    Any:







         """simple docstring"""



         for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             a__    = TFSwinModel.from_pretrained(__SCREAMING_SNAKE_CASE      )
             self.assertIsNotNone(__SCREAMING_SNAKE_CASE      )







@require_vision
@require_tf
class 						lowercase(unittest.TestCase					):



     @cached_property
     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         return (
             AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'      )
             if is_vision_available()
             else None
         )




     @slow
     def  lowercase__     (       self      )		->    List[Any]:







         """simple docstring"""



         a__    = TFSwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'      )
         a__    = self.default_image_processor

         a__    = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
         a__    = image_processor(images=__SCREAMING_SNAKE_CASE    ,							return_tensors='tf'      )

         # forward pass
         a__    = model(__SCREAMING_SNAKE_CASE      )

         # verify the logits
         a__    = tf.TensorShape((1, 1_0_0_0)      )
         self.assertEqual(outputs.logits.shape    ,							__SCREAMING_SNAKE_CASE      )
         a__    = tf.constant([-0.09_48, -0.64_54, -0.09_21]      )
         self.assertTrue(np.allclose(outputs.logits[0, :3]    ,							__SCREAMING_SNAKE_CASE    ,							atol=1e-4      )      )




"""simple docstring"""




# 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


a		:					Tuple    	=					os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
a		:					Union[str, Any]    	=					os.path.join(hf_cache_home, 'accelerate')
a		:					Dict    	=					os.path.join(cache_dir, 'default_config.yaml')
a		:					List[str]    	=					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):
    a		:					Tuple    	=					default_yaml_config_file
else:
    a		:					Dict    	=					default_json_config_file



def 						__magic_name__		(				UpperCamelCase    :		Tuple    )    ->	Union[str, Any]:
    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:
        a__    = 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
            ):
                a__    = ClusterConfig
            else:
                a__    = 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
            ):
                a__    = ClusterConfig
            else:
                a__    = SageMakerConfig
            return config_class.from_yaml_file(yaml_file=UpperCamelCase    )







@dataclass
class 						lowercase:
     __snake_case:  ComputeEnvironment
     __snake_case:  Union[DistributedType, SageMakerDistributedType]
     __snake_case:  str
     __snake_case:  bool



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



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



     @classmethod
     def  lowercase__     (       cls    ,							__SCREAMING_SNAKE_CASE=None      )		->    Dict:







         """simple docstring"""



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



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    int:







         """simple docstring"""



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



     @classmethod
     def  lowercase__     (       cls    ,							__SCREAMING_SNAKE_CASE=None      )		->    Optional[Any]:







         """simple docstring"""



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

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



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    List[Any]:







         """simple docstring"""



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




     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



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







@dataclass
class 						lowercase(_lowercase					):
     __snake_case:  int
     __snake_case:  int  				=    0
     __snake_case:  int  				=    1
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[int]  				=    None
     __snake_case:  Optional[str]  				=    "static"
     __snake_case:  Optional[bool]  				=    False
     __snake_case:  str  				=    "main"

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

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

     # args for dynamo
     __snake_case:  dict  				=    None



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







         """simple docstring"""



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







@dataclass
class 						lowercase(_lowercase					):
     __snake_case:  str
     __snake_case:  str
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[str]  				=    None
     __snake_case:  str  				=    "us-east-1"
     __snake_case:  int  				=    1
     __snake_case:  str  				=    "all"
     __snake_case:  str  				=    f"accelerate-sagemaker-{num_machines}"
     __snake_case:  str  				=    SAGEMAKER_PYTORCH_VERSION
     __snake_case:  str  				=    SAGEMAKER_TRANSFORMERS_VERSION
     __snake_case:  str  				=    SAGEMAKER_PYTHON_VERSION
     __snake_case:  str  				=    None
     __snake_case:  str  				=    None
     __snake_case:  dict  				=    None
     __snake_case:  dict  				=    None


