


'''simple docstring'''

import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
a_  :    Tuple      =			logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=2.0.0""", """To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt""")





def __snake_case (				UpperCAmelCase_						:						Optional[int] ,    UpperCAmelCase_						:						Optional[Any] ,    UpperCAmelCase_						:						Dict=0		):
 lowerCamelCase_								=  (size, size) if isinstance(UpperCAmelCase_ ,    UpperCAmelCase_		) else size
 lowerCamelCase_			,lowerCamelCase_								=  img.size
 lowerCamelCase_								=  size[1] - original_height if original_height < size[1] else 0
 lowerCamelCase_								=  size[0] - original_width if original_width < size[0] else 0
 lowerCamelCase_								=  functional.pad(UpperCAmelCase_ ,    (0, 0, pad_width, pad_height) ,    fill=UpperCAmelCase_		)
 return img





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  transforms







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   for t in self.transforms:
    lowerCamelCase_			,lowerCamelCase_								=  t(UpperCamelCase      ,  UpperCamelCase					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self					):







   """simple docstring"""
   pass







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  size







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  functional.resize(UpperCamelCase      ,  self.size					)
   lowerCamelCase_								=  functional.resize(UpperCamelCase      ,  self.size      ,  interpolation=transforms.InterpolationMode.NEAREST					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase      ,  UpperCamelCase=None					):







   """simple docstring"""
   lowerCamelCase_								=  min_size
   if max_size is None:
    lowerCamelCase_								=  min_size
   lowerCamelCase_								=  max_size







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  random.randint(self.min_size      ,  self.max_size					)
   lowerCamelCase_								=  functional.resize(UpperCamelCase      ,  UpperCamelCase					)
   lowerCamelCase_								=  functional.resize(UpperCamelCase      ,  UpperCamelCase      ,  interpolation=transforms.InterpolationMode.NEAREST					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  size if isinstance(UpperCamelCase      ,  UpperCamelCase					) else (size, size)







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  pad_if_smaller(UpperCamelCase      ,  self.size					)
   lowerCamelCase_								=  pad_if_smaller(UpperCamelCase      ,  self.size      ,  fill=255					)
   lowerCamelCase_								=  transforms.RandomCrop.get_params(UpperCamelCase      ,  self.size					)
   lowerCamelCase_								=  functional.crop(UpperCamelCase      ,  *UpperCamelCase					)
   lowerCamelCase_								=  functional.crop(UpperCamelCase      ,  *UpperCamelCase					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  flip_prob







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   if random.random() < self.flip_prob:
    lowerCamelCase_								=  functional.hflip(UpperCamelCase					)
    lowerCamelCase_								=  functional.hflip(UpperCamelCase					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  functional.pil_to_tensor(UpperCamelCase					)
   lowerCamelCase_								=  torch.as_tensor(np.array(UpperCamelCase					)      ,  dtype=torch.intaa					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  dtype







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  functional.convert_image_dtype(UpperCamelCase      ,  self.dtype					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  mean
   lowerCamelCase_								=  std







  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  functional.normalize(UpperCamelCase      ,  mean=self.mean      ,  std=self.std					)
   return image, target





class 					snake_case   :





  """simple docstring"""




  def __call__(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   if not isinstance(UpperCamelCase      ,  np.ndarray					):
    lowerCamelCase_								=  np.array(UpperCamelCase					).astype(np.uinta					)
   # avoid using underflow conversion
   lowerCamelCase_								=  255
   lowerCamelCase_								=  target - 1
   lowerCamelCase_								=  255

   lowerCamelCase_								=  Image.fromarray(UpperCamelCase					)
   return image, target





@dataclass
class 					snake_case   :





  """simple docstring"""




  _lowerCamelCase		   =  field(
      default="segments/sidewalk-semantic"      ,						metadata={
          "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
      }      ,						)
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}      )
  _lowerCamelCase		   =  field(
      default=0.15      ,						metadata={"help": "Percent to split off of train for validation."}      )
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of training examples to this "
              "value if set."
          )
      }      ,						)
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
              "value if set."
          )
      }      ,						)
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}      ,						)






  def   snake_case		(   self					):







   """simple docstring"""
   if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
    raise ValueError(
        "You must specify either a dataset name from the hub or a train and/or validation directory."					)





@dataclass
class 					snake_case   :





  """simple docstring"""




  _lowerCamelCase		   =  field(
      default="nvidia/mit-b0"      ,						metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}      ,						)
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={"help": "Pretrained config name or path if not the same as model_name"}      )
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}      )
  _lowerCamelCase		   =  field(
      default="main"      ,						metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}      ,						)
  _lowerCamelCase		   =  field(default=lowercase      ,						metadata={"help": "Name or path of preprocessor config."}      )
  _lowerCamelCase		   =  field(
      default=lowercase      ,						metadata={
          "help": (
              "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
              "with private models)."
          )
      }      ,						)





def __snake_case (				):
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 lowerCamelCase_								=  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
 if len(sys.argv		) == 2 and sys.argv[1].endswith(".json"		):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  lowerCamelCase_			,lowerCamelCase_			,lowerCamelCase_								=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
 else:
  lowerCamelCase_			,lowerCamelCase_			,lowerCamelCase_								=  parser.parse_args_into_dataclasses()

 # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
 # information sent is the one passed as arguments along with your Python/PyTorch versions.
 send_example_telemetry("run_semantic_segmentation" ,    UpperCAmelCase_ ,    UpperCAmelCase_		)

 # Setup logging
 logging.basicConfig(
     format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" ,    datefmt="%m/%d/%Y %H:%M:%S" ,    handlers=[logging.StreamHandler(sys.stdout		)] ,    )

 if training_args.should_log:
  # The default of training_args.log_level is passive, so we set log level at info here to have that default.
  transformers.utils.logging.set_verbosity_info()

 lowerCamelCase_								=  training_args.get_process_log_level()
 logger.setLevel(UpperCAmelCase_		)
 transformers.utils.logging.set_verbosity(UpperCAmelCase_		)
 transformers.utils.logging.enable_default_handler()
 transformers.utils.logging.enable_explicit_format()

 # Log on each process the small summary:
 logger.warning(
     F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
     + F'''distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}'''		)
 logger.info(F'''Training/evaluation parameters {training_args}'''		)

 # Detecting last checkpoint.
 lowerCamelCase_								=  None
 if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
  lowerCamelCase_								=  get_last_checkpoint(training_args.output_dir		)
  if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
   raise ValueError(
       F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
       "Use --overwrite_output_dir to overcome."		)
  elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
   logger.info(
       F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
       "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."		)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
 lowerCamelCase_								=  load_dataset(data_args.dataset_name ,    cache_dir=model_args.cache_dir		)

 # Rename column names to standardized names (only "image" and "label" need to be present)
 if "pixel_values" in dataset["train"].column_names:
  lowerCamelCase_								=  dataset.rename_columns({"pixel_values": "image"}		)
 if "annotation" in dataset["train"].column_names:
  lowerCamelCase_								=  dataset.rename_columns({"annotation": "label"}		)

 # If we don't have a validation split, split off a percentage of train as validation.
 lowerCamelCase_								=  None if "validation" in dataset.keys() else data_args.train_val_split
 if isinstance(data_args.train_val_split ,    UpperCAmelCase_		) and data_args.train_val_split > 0.0:
  lowerCamelCase_								=  dataset["train"].train_test_split(data_args.train_val_split		)
  lowerCamelCase_								=  split["train"]
  lowerCamelCase_								=  split["test"]

 # Prepare label mappings.
 # We'll include these in the model's config to get human readable labels in the Inference API.
 if data_args.dataset_name == "scene_parse_150":
  lowerCamelCase_								=  "huggingface/label-files"
  lowerCamelCase_								=  "ade20k-id2label.json"
 else:
  lowerCamelCase_								=  data_args.dataset_name
  lowerCamelCase_								=  "id2label.json"
 lowerCamelCase_								=  json.load(open(hf_hub_download(UpperCAmelCase_ ,    UpperCAmelCase_ ,    repo_type="dataset"		) ,    "r"		)		)
 lowerCamelCase_								=  {int(UpperCAmelCase_		): v for k, v in idalabel.items()}
 lowerCamelCase_								=  {v: str(UpperCAmelCase_		) for k, v in idalabel.items()}

 # Load the mean IoU metric from the datasets package
 lowerCamelCase_								=  evaluate.load("mean_iou"		)

 # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
 # predictions and label_ids field) and has to return a dictionary string to float.
 @torch.no_grad()
 def compute_metrics(UpperCAmelCase_						:						Union[str, Any]		):
  lowerCamelCase_			,lowerCamelCase_								=  eval_pred
  lowerCamelCase_								=  torch.from_numpy(UpperCAmelCase_		)
  # scale the logits to the size of the label
  lowerCamelCase_								=  nn.functional.interpolate(
      UpperCAmelCase_ ,    size=labels.shape[-2:] ,    mode="bilinear" ,    align_corners=UpperCAmelCase_ ,    ).argmax(dim=1		)

  lowerCamelCase_								=  logits_tensor.detach().cpu().numpy()
  lowerCamelCase_								=  metric.compute(
      predictions=UpperCAmelCase_ ,    references=UpperCAmelCase_ ,    num_labels=len(UpperCAmelCase_		) ,    ignore_index=0 ,    reduce_labels=image_processor.do_reduce_labels ,    )
  # add per category metrics as individual key-value pairs
  lowerCamelCase_								=  metrics.pop("per_category_accuracy"		).tolist()
  lowerCamelCase_								=  metrics.pop("per_category_iou"		).tolist()

  metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(UpperCAmelCase_		)}		)
  metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(UpperCAmelCase_		)}		)

  return metrics

 lowerCamelCase_								=  AutoConfig.from_pretrained(
     model_args.config_name or model_args.model_name_or_path ,    labelaid=UpperCAmelCase_ ,    idalabel=UpperCAmelCase_ ,    cache_dir=model_args.cache_dir ,    revision=model_args.model_revision ,    use_auth_token=True if model_args.use_auth_token else None ,    )
 lowerCamelCase_								=  AutoModelForSemanticSegmentation.from_pretrained(
     model_args.model_name_or_path ,    from_tf=bool(".ckpt" in model_args.model_name_or_path		) ,    config=UpperCAmelCase_ ,    cache_dir=model_args.cache_dir ,    revision=model_args.model_revision ,    use_auth_token=True if model_args.use_auth_token else None ,    )
 lowerCamelCase_								=  AutoImageProcessor.from_pretrained(
     model_args.image_processor_name or model_args.model_name_or_path ,    cache_dir=model_args.cache_dir ,    revision=model_args.model_revision ,    use_auth_token=True if model_args.use_auth_token else None ,    )

 # Define torchvision transforms to be applied to each image + target.
 # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
 # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
 if "shortest_edge" in image_processor.size:
  # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
  lowerCamelCase_								=  (image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
 else:
  lowerCamelCase_								=  (image_processor.size["height"], image_processor.size["width"])
 lowerCamelCase_								=  Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         RandomCrop(size=UpperCAmelCase_		),
         RandomHorizontalFlip(flip_prob=0.5		),
         PILToTensor(),
         ConvertImageDtype(torch.float		),
         Normalize(mean=image_processor.image_mean ,    std=image_processor.image_std		),
     ]		)
 # Define torchvision transform to be applied to each image.
 # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
 lowerCamelCase_								=  Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         Resize(size=UpperCAmelCase_		),
         PILToTensor(),
         ConvertImageDtype(torch.float		),
         Normalize(mean=image_processor.image_mean ,    std=image_processor.image_std		),
     ]		)

 def preprocess_train(UpperCAmelCase_						:						Union[str, Any]		):
  lowerCamelCase_								=  []
  lowerCamelCase_								=  []
  for image, target in zip(example_batch["image"] ,    example_batch["label"]		):
   lowerCamelCase_			,lowerCamelCase_								=  train_transforms(image.convert("RGB"		) ,    UpperCAmelCase_		)
   pixel_values.append(UpperCAmelCase_		)
   labels.append(UpperCAmelCase_		)

  lowerCamelCase_								=  {}
  lowerCamelCase_								=  torch.stack(UpperCAmelCase_		)
  lowerCamelCase_								=  torch.stack(UpperCAmelCase_		)

  return encoding

 def preprocess_val(UpperCAmelCase_						:						Any		):
  lowerCamelCase_								=  []
  lowerCamelCase_								=  []
  for image, target in zip(example_batch["image"] ,    example_batch["label"]		):
   lowerCamelCase_			,lowerCamelCase_								=  val_transforms(image.convert("RGB"		) ,    UpperCAmelCase_		)
   pixel_values.append(UpperCAmelCase_		)
   labels.append(UpperCAmelCase_		)

  lowerCamelCase_								=  {}
  lowerCamelCase_								=  torch.stack(UpperCAmelCase_		)
  lowerCamelCase_								=  torch.stack(UpperCAmelCase_		)

  return encoding

 if training_args.do_train:
  if "train" not in dataset:
   raise ValueError("--do_train requires a train dataset"		)
  if data_args.max_train_samples is not None:
   lowerCamelCase_								=  (
       dataset["train"].shuffle(seed=training_args.seed		).select(range(data_args.max_train_samples		)		)
   )
  # Set the training transforms
  dataset["train"].set_transform(UpperCAmelCase_		)

 if training_args.do_eval:
  if "validation" not in dataset:
   raise ValueError("--do_eval requires a validation dataset"		)
  if data_args.max_eval_samples is not None:
   lowerCamelCase_								=  (
       dataset["validation"].shuffle(seed=training_args.seed		).select(range(data_args.max_eval_samples		)		)
   )
  # Set the validation transforms
  dataset["validation"].set_transform(UpperCAmelCase_		)

 # Initalize our trainer
 lowerCamelCase_								=  Trainer(
     model=UpperCAmelCase_ ,    args=UpperCAmelCase_ ,    train_dataset=dataset["train"] if training_args.do_train else None ,    eval_dataset=dataset["validation"] if training_args.do_eval else None ,    compute_metrics=UpperCAmelCase_ ,    tokenizer=UpperCAmelCase_ ,    data_collator=UpperCAmelCase_ ,    )

 # Training
 if training_args.do_train:
  lowerCamelCase_								=  None
  if training_args.resume_from_checkpoint is not None:
   lowerCamelCase_								=  training_args.resume_from_checkpoint
  elif last_checkpoint is not None:
   lowerCamelCase_								=  last_checkpoint
  lowerCamelCase_								=  trainer.train(resume_from_checkpoint=UpperCAmelCase_		)
  trainer.save_model()
  trainer.log_metrics("train" ,    train_result.metrics		)
  trainer.save_metrics("train" ,    train_result.metrics		)
  trainer.save_state()

 # Evaluation
 if training_args.do_eval:
  lowerCamelCase_								=  trainer.evaluate()
  trainer.log_metrics("eval" ,    UpperCAmelCase_		)
  trainer.save_metrics("eval" ,    UpperCAmelCase_		)

 # Write model card and (optionally) push to hub
 lowerCamelCase_								=  {
     "finetuned_from": model_args.model_name_or_path,
     "dataset": data_args.dataset_name,
     "tags": ["image-segmentation", "vision"],
 }
 if training_args.push_to_hub:
  trainer.push_to_hub(**UpperCAmelCase_		)
 else:
  trainer.create_model_card(**UpperCAmelCase_		)


if __name__ == "__main__":
     main()






'''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_  :    Dict      =			os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
a_  :    Dict      =			os.path.join(hf_cache_home, """accelerate""")
a_  :    Optional[int]      =			os.path.join(cache_dir, """default_config.yaml""")
a_  :    int      =			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_  :    str      =			default_yaml_config_file
else:
     a_  :    str      =			default_json_config_file





def __snake_case (				UpperCAmelCase_						:						Optional[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:
  lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  SageMakerConfig
   return config_class.from_yaml_file(yaml_file=UpperCAmelCase_		)





@dataclass
class 					snake_case   :





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42






  def   snake_case		(   self					):







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






  @classmethod
  def   snake_case		(   cls      ,  UpperCamelCase=None					):







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






  def   snake_case		(   self      ,  UpperCamelCase					):







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






  @classmethod
  def   snake_case		(   cls      ,  UpperCamelCase=None					):







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

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






  def   snake_case		(   self      ,  UpperCamelCase					):







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







  def   snake_case		(   self					):







   """simple docstring"""
   if isinstance(self.compute_environment      ,  UpperCamelCase					):
    lowerCamelCase_								=  ComputeEnvironment(self.compute_environment					)
   if isinstance(self.distributed_type      ,  UpperCamelCase					):
    if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
     lowerCamelCase_								=  SageMakerDistributedType(self.distributed_type					)
    else:
     lowerCamelCase_								=  DistributedType(self.distributed_type					)
   if self.dynamo_config is None:
    lowerCamelCase_								=  {}





@dataclass
class 					snake_case   (   lowercase      ):





  """simple docstring"""




  _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   snake_case		(   self					):







   """simple docstring"""
   if self.deepspeed_config is None:
    lowerCamelCase_								=  {}
   if self.fsdp_config is None:
    lowerCamelCase_								=  {}
   if self.megatron_lm_config is None:
    lowerCamelCase_								=  {}
   if self.ipex_config is None:
    lowerCamelCase_								=  {}
   return super().__post_init__()





@dataclass
class 					snake_case   (   lowercase      ):





  """simple docstring"""




  _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



