






# 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 warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType




class     _lowerCAmelCase(	UpperCAmelCase_ ):





       """simple docstring"""







       def __init__( self  ,      _lowerCamelCase							):
         UpperCamelCase_: Any   				=    data





       def __iter__( self							):
         for element in self.data:
           yield element







def   snake_case (UpperCAmelCase__=True  )	->    Union[str, Any]:
  UpperCamelCase_: Optional[Any]   				=    Accelerator(even_batches=UpperCAmelCase__  )
  assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
  return accelerator

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__ = False  )	->    Optional[Any]:
  if iterable:
    UpperCamelCase_: int   				=    DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase__  )  )  )
  else:
    UpperCamelCase_: Optional[int]   				=    TensorDataset(torch.as_tensor(range(UpperCAmelCase__  )  )  )

  UpperCamelCase_: Dict   				=    DataLoader(UpperCAmelCase__     ,   batch_size=UpperCAmelCase__  )
  UpperCamelCase_: Union[str, Any]   				=    accelerator.prepare(UpperCAmelCase__  )

  return dl

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__     ,   )	->    int:
  UpperCamelCase_: Union[str, Any]   				=    create_dataloader(accelerator=UpperCAmelCase__     ,   dataset_size=UpperCAmelCase__     ,   batch_size=UpperCAmelCase__  )

  UpperCamelCase_: Any   				=    [len(batch[0]  ) for batch in dl]

  if accelerator.process_index == 0:
    assert batch_sizes == process_0_expected_batch_sizes
  elif accelerator.process_index == 1:
    assert batch_sizes == process_1_expected_batch_sizes

def   snake_case ()	->    List[str]:
  UpperCamelCase_: Optional[int]   				=    create_accelerator()

  # without padding, we would expect a different number of batches
  verify_dataloader_batch_sizes(
      UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1     ,   process_0_expected_batch_sizes=[1, 1]     ,   process_1_expected_batch_sizes=[1, 1]     ,   )

  # without padding, we would expect the same number of batches, but different sizes
  verify_dataloader_batch_sizes(
      UpperCAmelCase__     ,   dataset_size=7     ,   batch_size=2     ,   process_0_expected_batch_sizes=[2, 2]     ,   process_1_expected_batch_sizes=[2, 2]     ,   )

def   snake_case ()	->    str:
  UpperCamelCase_: Optional[int]   				=    create_accelerator(even_batches=UpperCAmelCase__  )

  verify_dataloader_batch_sizes(
      UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1     ,   process_0_expected_batch_sizes=[1, 1]     ,   process_1_expected_batch_sizes=[1]     ,   )

  verify_dataloader_batch_sizes(
      UpperCAmelCase__     ,   dataset_size=7     ,   batch_size=2     ,   process_0_expected_batch_sizes=[2, 2]     ,   process_1_expected_batch_sizes=[2, 1]     ,   )

def   snake_case ()	->    int:
  UpperCamelCase_: str   				=    create_accelerator(even_batches=UpperCAmelCase__  )

  UpperCamelCase_: int   				=    torch.nn.Linear(1     ,   1  )
  UpperCamelCase_: Dict   				=    accelerator.prepare(UpperCAmelCase__  )

  UpperCamelCase_: List[Any]   				=    create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1  )

  UpperCamelCase_: str   				=    []
  with accelerator.join_uneven_inputs([ddp_model]  ):
    for batch_idx, batch in enumerate(UpperCAmelCase__  ):
      UpperCamelCase_: Any   				=    ddp_model(batch[0].float()  )
      UpperCamelCase_: str   				=    output.sum()
      loss.backward()
      batch_idxs.append(UpperCAmelCase__  )

  accelerator.wait_for_everyone()

  if accelerator.process_index == 0:
    assert batch_idxs == [0, 1]
  elif accelerator.process_index == 1:
    assert batch_idxs == [0]

def   snake_case (UpperCAmelCase__  )	->    str:
  with warnings.catch_warnings(record=UpperCAmelCase__  ) as w:
    with accelerator.join_uneven_inputs([Mock()]  ):
      pass

    assert issubclass(w[-1].category     ,   UpperCAmelCase__  )
    assert "only supported for multi-GPU" in str(w[-1].message  )

def   snake_case ()	->    Any:
  UpperCamelCase_: List[str]   				=    True
  UpperCamelCase_: List[Any]   				=    False
  UpperCamelCase_: List[str]   				=    create_accelerator(even_batches=UpperCAmelCase__  )
  UpperCamelCase_: Dict   				=    torch.nn.Linear(1     ,   1  )
  UpperCamelCase_: Any   				=    accelerator.prepare(UpperCAmelCase__  )
  UpperCamelCase_: Optional[Any]   				=    create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1  )
  UpperCamelCase_: int   				=    create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1  )

  with accelerator.join_uneven_inputs([ddp_model]     ,   even_batches=UpperCAmelCase__  ):
    UpperCamelCase_: Optional[int]   				=    train_dl.batch_sampler.even_batches
    UpperCamelCase_: List[Any]   				=    valid_dl.batch_sampler.even_batches

  assert train_dl_overridden_value == overridden_even_batches
  assert valid_dl_overridden_value == overridden_even_batches
  assert train_dl.batch_sampler.even_batches == default_even_batches
  assert valid_dl.batch_sampler.even_batches == default_even_batches

def   snake_case ()	->    Any:
  UpperCamelCase_: int   				=    True
  UpperCamelCase_: Any   				=    False
  UpperCamelCase_: str   				=    create_accelerator(even_batches=UpperCAmelCase__  )
  UpperCamelCase_: Tuple   				=    torch.nn.Linear(1     ,   1  )
  UpperCamelCase_: Optional[Any]   				=    accelerator.prepare(UpperCAmelCase__  )
  create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1     ,   iterable=UpperCAmelCase__  )
  UpperCamelCase_: Optional[int]   				=    create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1  )

  with warnings.catch_warnings():
    warnings.filterwarnings('ignore'  )
    try:
      with accelerator.join_uneven_inputs([ddp_model]     ,   even_batches=UpperCAmelCase__  ):
        UpperCamelCase_: Dict   				=    batch_dl.batch_sampler.even_batches
    except AttributeError:
      # ensure attribute error is not raised when processing iterable dl
      raise AssertionError

  assert batch_dl_overridden_value == overridden_even_batches
  assert batch_dl.batch_sampler.even_batches == default_even_batches

def   snake_case ()	->    Union[str, Any]:
  UpperCamelCase_: List[Any]   				=    create_accelerator()
  UpperCamelCase_: int   				=    torch.nn.Linear(1     ,   1  )
  UpperCamelCase_: Tuple   				=    accelerator.prepare(UpperCAmelCase__  )
  create_dataloader(UpperCAmelCase__     ,   dataset_size=3     ,   batch_size=1     ,   iterable=UpperCAmelCase__  )

  with warnings.catch_warnings(record=UpperCAmelCase__  ) as w:
    with accelerator.join_uneven_inputs([ddp_model]     ,   even_batches=UpperCAmelCase__  ):
      pass

    assert issubclass(w[-1].category     ,   UpperCAmelCase__  )
    assert "only supported for map-style datasets" in str(w[-1].message  )

def   snake_case ()	->    Dict:
  UpperCamelCase_: Tuple   				=    create_accelerator()

  accelerator.print('Test that even_batches variable ensures uniform batches across processes'  )
  test_default_ensures_even_batch_sizes()

  accelerator.print('Run tests with even_batches disabled'  )
  test_can_disable_even_batches()

  accelerator.print('Test joining uneven inputs'  )
  test_can_join_uneven_inputs()

  accelerator.print('Test overriding even_batches when joining uneven inputs'  )
  test_join_can_override_even_batches()

  accelerator.print('Test overriding even_batches for mixed dataloader types'  )
  test_join_can_override_for_mixed_type_dataloaders()

  accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders'  )
  test_join_raises_warning_for_iterable_when_overriding_even_batches()

  accelerator.print('Test join with non DDP distributed raises warning'  )
  UpperCamelCase_: List[Any]   				=    accelerator.state.distributed_type
  UpperCamelCase_: List[str]   				=    DistributedType.FSDP
  test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase__  )
  UpperCamelCase_: Optional[Any]   				=    original_state


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 argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


A_		:		Any		     =			'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'

def   snake_case ()	->    Union[str, Any]:
  UpperCamelCase_: Tuple   				=    _ask_options(
      'In which compute environment are you running?'     ,   ['This machine', 'AWS (Amazon SageMaker)']     ,   _convert_compute_environment     ,   )
  if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
    UpperCamelCase_: List[str]   				=    get_sagemaker_input()
  else:
    UpperCamelCase_: List[str]   				=    get_cluster_input()
  return config

def   snake_case (UpperCAmelCase__=None  )	->    Union[str, Any]:
  if subparsers is not None:
    UpperCamelCase_: List[Any]   				=    subparsers.add_parser('config'     ,   description=UpperCAmelCase__  )
  else:
    UpperCamelCase_: List[Any]   				=    argparse.ArgumentParser('Accelerate config command'     ,   description=UpperCAmelCase__  )

  parser.add_argument(
      '--config_file'     ,   default=UpperCAmelCase__     ,   help=(
          'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
          'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
          'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
          'with \'huggingface\'.'
      )     ,   )

  if subparsers is not None:
    parser.set_defaults(func=UpperCAmelCase__  )
  return parser

def   snake_case (UpperCAmelCase__  )	->    List[Any]:
  UpperCamelCase_: Union[str, Any]   				=    get_user_input()
  if args.config_file is not None:
    UpperCamelCase_: Tuple   				=    args.config_file
  else:
    if not os.path.isdir(UpperCAmelCase__  ):
      os.makedirs(UpperCAmelCase__  )
    UpperCamelCase_: Dict   				=    default_yaml_config_file

  if config_file.endswith('.json'  ):
    config.to_json_file(UpperCAmelCase__  )
  else:
    config.to_yaml_file(UpperCAmelCase__  )
  print(F'''accelerate configuration saved at {config_file}'''  )

def   snake_case ()	->    str:
  UpperCamelCase_: Tuple   				=    config_command_parser()
  UpperCamelCase_: int   				=    parser.parse_args()
  config_command(UpperCAmelCase__  )


if __name__ == "__main__":
   main()