




"""simple docstring"""







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


SCREAMING_SNAKE_CASE_      =					os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
SCREAMING_SNAKE_CASE_      =					os.path.join(hf_cache_home, 'accelerate')
SCREAMING_SNAKE_CASE_      =					os.path.join(cache_dir, 'default_config.yaml')
SCREAMING_SNAKE_CASE_      =					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):
    SCREAMING_SNAKE_CASE_      =					default_yaml_config_file
else:
    SCREAMING_SNAKE_CASE_      =					default_json_config_file





def     __snake_case   (							_lowercase						):


    """simple docstring"""







    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:
        UpperCamelCase										=  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
            ):
                UpperCamelCase										=  ClusterConfig
            else:
                UpperCamelCase										=  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
            ):
                UpperCamelCase										=  ClusterConfig
            else:
                UpperCamelCase										=  SageMakerConfig
            return config_class.from_yaml_file(yaml_file=_lowercase						)

@dataclass
class 							snake_case_ :







   """simple docstring"""




   A_										=					42
   A_										=					42
   A_										=					42
   A_										=					42







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







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







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_)							->      Any:
       with open(lowerCamelCase_					,				'''w'''					,				encoding='''utf-8''') as f:
           UpperCamelCase										=  json.dumps(self.to_dict()					,				indent=2					,				sort_keys=lowerCamelCase_) + '''\n'''
           f.write(lowerCamelCase_)







   @classmethod
   def      UpperCAmelCase__ (		cls					,				lowerCamelCase_=None)							->      List[str]:
       UpperCamelCase										=  default_yaml_config_file if yaml_file is None else yaml_file
       with open(lowerCamelCase_					,				'''r'''					,				encoding='''utf-8''') as f:
           UpperCamelCase										=  yaml.safe_load(lowerCamelCase_)
       if "compute_environment" not in config_dict:
           UpperCamelCase										=  ComputeEnvironment.LOCAL_MACHINE

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







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







   def      UpperCAmelCase__ (		self)							->      Optional[int]:
       if isinstance(self.compute_environment					,				lowerCamelCase_):
           UpperCamelCase										=  ComputeEnvironment(self.compute_environment)
       if isinstance(self.distributed_type					,				lowerCamelCase_):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
               UpperCamelCase										=  SageMakerDistributedType(self.distributed_type)
           else:
               UpperCamelCase										=  DistributedType(self.distributed_type)
       if self.dynamo_config is None:
           UpperCamelCase										=  {}

@dataclass
class 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   A_										=					42
   A_										=					0
   A_										=					1
   A_										=					None
   A_										=					None
   A_										=					None
   A_										=					'''static'''
   A_										=					False
   A_										=					'''main'''

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

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

   # args for dynamo
   A_										=					None







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

@dataclass
class 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   A_										=					42
   A_										=					42
   A_										=					None
   A_										=					None
   A_										=					'''us-east-1'''
   A_										=					1
   A_										=					'''all'''
   A_										=					f"""accelerate-sagemaker-{num_machines}"""
   A_										=					SAGEMAKER_PYTORCH_VERSION
   A_										=					SAGEMAKER_TRANSFORMERS_VERSION
   A_										=					SAGEMAKER_PYTHON_VERSION
   A_										=					None
   A_										=					None
   A_										=					None
   A_										=					None





"""simple docstring"""







import os
import sys
from pathlib import Path

import pytest

from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node

from .utils import execute_subprocess_async, get_torch_dist_unique_port, require_torch





def     __snake_case   (							):


    """simple docstring"""







    UpperCamelCase										=  Dataset.from_dict({'''i''': range(17						)}						)
    UpperCamelCase										=  len(_lowercase						)
    UpperCamelCase										=  3
    UpperCamelCase										=  [
        split_dataset_by_node(_lowercase ,rank=_lowercase ,world_size=_lowercase						) for rank in range(_lowercase						)
    ]
    assert sum(len(_lowercase						) for ds in datasets_per_rank						) == full_size
    assert len({tuple(x.values()						) for ds in datasets_per_rank for x in ds}						) == full_size





def     __snake_case   (							):


    """simple docstring"""







    def gen():
        return ({"i": i} for i in range(17						))

    UpperCamelCase										=  3
    UpperCamelCase										=  IterableDataset.from_generator(_lowercase						)
    UpperCamelCase										=  len(list(_lowercase						)						)
    UpperCamelCase										=  [
        split_dataset_by_node(_lowercase ,rank=_lowercase ,world_size=_lowercase						) for rank in range(_lowercase						)
    ]
    assert sum(len(list(_lowercase						)						) for ds in datasets_per_rank						) == full_size
    assert len({tuple(x.values()						) for ds in datasets_per_rank for x in ds}						) == full_size





@pytest.mark.parametrize('''shards_per_node''' ,[1, 2, 3]						)
def     __snake_case   (							_lowercase						):


    """simple docstring"""







    def gen(_lowercase						):
        for shard in shards:
            yield from ({"i": i, "shard": shard} for i in range(17						))

    UpperCamelCase										=  3
    UpperCamelCase										=  shards_per_node * world_size
    UpperCamelCase										=  {'''shards''': [f'shard_{shard_idx}.txt' for shard_idx in range(_lowercase						)]}
    UpperCamelCase										=  IterableDataset.from_generator(_lowercase ,gen_kwargs=_lowercase						)
    UpperCamelCase										=  len(list(_lowercase						)						)
    assert full_ds.n_shards == world_size * shards_per_node
    UpperCamelCase										=  [
        split_dataset_by_node(_lowercase ,rank=_lowercase ,world_size=_lowercase						) for rank in range(_lowercase						)
    ]
    assert [ds.n_shards for ds in datasets_per_rank] == [shards_per_node] * world_size
    assert sum(len(list(_lowercase						)						) for ds in datasets_per_rank						) == full_size
    assert len({tuple(x.values()						) for ds in datasets_per_rank for x in ds}						) == full_size





def     __snake_case   (							):


    """simple docstring"""







    def gen():
        return ({"i": i} for i in range(17						))

    UpperCamelCase										=  2
    UpperCamelCase										=  IterableDataset.from_generator(_lowercase						)
    UpperCamelCase										=  len(list(_lowercase						)						)

    UpperCamelCase										=  split_dataset_by_node(_lowercase ,rank=0 ,world_size=_lowercase						).shuffle(seed=42						)
    assert len(list(_lowercase						)						) == 1 + full_size // world_size
    with pytest.raises(_lowercase						):
        split_dataset_by_node(_lowercase ,rank=0 ,world_size=_lowercase						).shuffle()

    UpperCamelCase										=  split_dataset_by_node(full_ds.shuffle(seed=42						) ,rank=0 ,world_size=_lowercase						)
    assert len(list(_lowercase						)						) == 1 + full_size // world_size
    with pytest.raises(_lowercase						):
        split_dataset_by_node(full_ds.shuffle() ,rank=0 ,world_size=_lowercase						)





@pytest.mark.parametrize('''streaming''' ,[False, True]						)
@require_torch
@pytest.mark.skipif(os.name == '''nt''' ,reason='''execute_subprocess_async doesn\'t support windows'''						)
@pytest.mark.integration
def     __snake_case   (							_lowercase						):


    """simple docstring"""







    UpperCamelCase										=  2
    UpperCamelCase										=  get_torch_dist_unique_port()
    UpperCamelCase										=  Path(_lowercase						).resolve().parent / '''distributed_scripts''' / '''launch_torch_distributed.py'''
    UpperCamelCase										=  f'\n        -m torch.distributed.launch\n        --nproc_per_node={nproc_per_node}\n        --master_port={master_port}\n        {test_script}\n    '.split()
    UpperCamelCase										=  f'\n        --streaming={streaming}\n    '.split()
    UpperCamelCase										=  [sys.executable] + distributed_args + args
    execute_subprocess_async(_lowercase ,env=os.environ.copy()						)





@pytest.mark.parametrize(
    '''nproc_per_node, num_workers''' ,[
        (2, 2),  # each node has 2 shards and each worker has 1 shards
        (3, 2),  # each node uses all the shards but skips examples, and each worker has 2 shards
    ] ,)
@require_torch
@pytest.mark.skipif(os.name == '''nt''' ,reason='''execute_subprocess_async doesn\'t support windows'''						)
@pytest.mark.integration
def     __snake_case   (							_lowercase ,_lowercase						):


    """simple docstring"""







    UpperCamelCase										=  True
    UpperCamelCase										=  get_torch_dist_unique_port()
    UpperCamelCase										=  Path(_lowercase						).resolve().parent / '''distributed_scripts''' / '''launch_torch_distributed.py'''
    UpperCamelCase										=  f'\n        -m torch.distributed.launch\n        --nproc_per_node={nproc_per_node}\n        --master_port={master_port}\n        {test_script}\n    '.split()
    UpperCamelCase										=  f'\n        --streaming={streaming}\n        --num_workers={num_workers}\n    '.split()
    UpperCamelCase										=  [sys.executable] + distributed_args + args
    execute_subprocess_async(_lowercase ,env=os.environ.copy()						)