


# 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  SCREAMING_SNAKE_CASE__  (				lowercase__			):
      def __init__(       self				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     )		->			Any:
             a_					:		Tuple							=  data

      def __iter__(       self				:       Union[str, Any]     )		->			Union[str, Any]:
             for element in self.data:
                    yield element







def        SCREAMING_SNAKE_CASE_						(			__A :			Union[str, Any]=True				)	->		Tuple:

       """simple docstring"""

       a_					:		Optional[Any]							=  Accelerator(even_batches=__A				)
       assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
       return accelerator







def        SCREAMING_SNAKE_CASE_						(			__A :			Accelerator  ,    __A :			int  ,    __A :			int  ,    __A :			bool = False				)	->		Any:

       """simple docstring"""

       if iterable:
              a_					:		Optional[int]							=  DummyIterableDataset(torch.as_tensor(range(__A				)				)				)
       else:
              a_					:		Optional[Any]							=  TensorDataset(torch.as_tensor(range(__A				)				)				)

       a_					:		Dict							=  DataLoader(__A  ,    batch_size=__A				)
       a_					:		Dict							=  accelerator.prepare(__A				)

       return dl







def        SCREAMING_SNAKE_CASE_						(			__A :			Accelerator  ,    __A :			int  ,    __A :			int  ,    __A :			List[int]  ,    __A :			List[int]  ,    )	->		Union[str, Any]:

       """simple docstring"""

       a_					:		int							=  create_dataloader(accelerator=__A  ,    dataset_size=__A  ,    batch_size=__A				)

       a_					:		str							=  [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        SCREAMING_SNAKE_CASE_						(			)	->		Optional[Any]:

       """simple docstring"""

       a_					:		List[Any]							=  create_accelerator()

       # without padding, we would expect a different number of batches
       verify_dataloader_batch_sizes(
           __A  ,    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(
           __A  ,    dataset_size=7  ,    batch_size=2  ,    process_0_expected_batch_sizes=[2, 2]  ,    process_1_expected_batch_sizes=[2, 2]  ,    )







def        SCREAMING_SNAKE_CASE_						(			)	->		Optional[Any]:

       """simple docstring"""

       a_					:		Tuple							=  create_accelerator(even_batches=__A				)

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

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







def        SCREAMING_SNAKE_CASE_						(			)	->		str:

       """simple docstring"""

       a_					:		List[str]							=  create_accelerator(even_batches=__A				)

       a_					:		List[str]							=  torch.nn.Linear(1  ,    1				)
       a_					:		Optional[int]							=  accelerator.prepare(__A				)

       a_					:		Any							=  create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1				)

       a_					:		Optional[int]							=  []
       with accelerator.join_uneven_inputs([ddp_model]				):
              for batch_idx, batch in enumerate(__A				):
                     a_					:		List[str]							=  ddp_model(batch[0].float()				)
                     a_					:		List[str]							=  output.sum()
                     loss.backward()
                     batch_idxs.append(__A				)

       accelerator.wait_for_everyone()

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







def        SCREAMING_SNAKE_CASE_						(			__A :			int				)	->		int:

       """simple docstring"""

       with warnings.catch_warnings(record=__A				) as w:
              with accelerator.join_uneven_inputs([Mock()]				):
                     pass

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







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

       """simple docstring"""

       a_					:		List[Any]							=  True
       a_					:		List[Any]							=  False
       a_					:		List[str]							=  create_accelerator(even_batches=__A				)
       a_					:		Optional[int]							=  torch.nn.Linear(1  ,    1				)
       a_					:		str							=  accelerator.prepare(__A				)
       a_					:		Optional[int]							=  create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1				)
       a_					:		Any							=  create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1				)

       with accelerator.join_uneven_inputs([ddp_model]  ,    even_batches=__A				):
              a_					:		Optional[Any]							=  train_dl.batch_sampler.even_batches
              a_					:		Dict							=  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        SCREAMING_SNAKE_CASE_						(			)	->		Optional[Any]:

       """simple docstring"""

       a_					:		List[str]							=  True
       a_					:		str							=  False
       a_					:		Any							=  create_accelerator(even_batches=__A				)
       a_					:		Any							=  torch.nn.Linear(1  ,    1				)
       a_					:		str							=  accelerator.prepare(__A				)
       create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1  ,    iterable=__A				)
       a_					:		Optional[int]							=  create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1				)

       with warnings.catch_warnings():
              warnings.filterwarnings('ignore'				)
              try:
                     with accelerator.join_uneven_inputs([ddp_model]  ,    even_batches=__A				):
                            a_					:		Union[str, Any]							=  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        SCREAMING_SNAKE_CASE_						(			)	->		List[str]:

       """simple docstring"""

       a_					:		Union[str, Any]							=  create_accelerator()
       a_					:		Any							=  torch.nn.Linear(1  ,    1				)
       a_					:		Union[str, Any]							=  accelerator.prepare(__A				)
       create_dataloader(__A  ,    dataset_size=3  ,    batch_size=1  ,    iterable=__A				)

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

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







def        SCREAMING_SNAKE_CASE_						(			)	->		Dict:

       """simple docstring"""

       a_					:		Any							=  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'				)
       a_					:		Optional[int]							=  accelerator.state.distributed_type
       a_					:		Optional[int]							=  DistributedType.FSDP
       test_join_raises_warning_for_non_ddp_distributed(__A				)
       a_					:		List[str]							=  original_state


if __name__ == "__main__":
   main()






import inspect
import re
from hashlib import shaaaa
from typing import Dict, List

from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql  # noqa F401
from .text import text







def        SCREAMING_SNAKE_CASE_						(			__A :			List[str]				)	->		str:

       """simple docstring"""

       a_					:		Tuple							=  []
       for line in lines:
              a_					:		Any							=  re.sub(R'#.*'  ,    ''  ,    __A				)  # remove comments
              if line:
                     filtered_lines.append(__A				)
       a_					:		Tuple							=  '\n'.join(__A				)

       # Make a hash from all this code
       a_					:		Tuple							=  full_str.encode('utf-8'				)
       return shaaaa(__A				).hexdigest()


# get importable module names and hash for caching
UpperCAmelCase_      : List[Any]  					=       {
    'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
    'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
    'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
    'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
    'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
    'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
    'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
    'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}

# Used to infer the module to use based on the data files extensions
UpperCAmelCase_      : Dict  					=       {
    '.csv': ('csv', {}),
    '.tsv': ('csv', {'sep': '\t'}),
    '.json': ('json', {}),
    '.jsonl': ('json', {}),
    '.parquet': ('parquet', {}),
    '.arrow': ('arrow', {}),
    '.txt': ('text', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
UpperCAmelCase_      : Optional[int]  					=       {'imagefolder', 'audiofolder'}

# Used to filter data files based on extensions given a module name
UpperCAmelCase_      : Dict[str, List[str]]  					=       {}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
   _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)

_MODULE_TO_EXTENSIONS["imagefolder"].append('.zip')
_MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')


