



# 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 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def __init__(							self    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  data



		def __iter__(							self						):







						"""simple docstring"""
						for element in self.data:
										yield element







def     UpperCAmelCase_		(					snake_case__=True					)	->     str:



				"""simple docstring"""





				lowerCAmelCase__		  =  Accelerator(even_batches=snake_case__					)
				assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
				return accelerator







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__    ,			snake_case__ = False					)	->     List[Any]:



				"""simple docstring"""





				if iterable:
								lowerCAmelCase__		  =  DummyIterableDataset(torch.as_tensor(range(snake_case__					)					)					)
				else:
								lowerCAmelCase__		  =  TensorDataset(torch.as_tensor(range(snake_case__					)					)					)

				lowerCAmelCase__		  =  DataLoader(snake_case__    ,			batch_size=snake_case__					)
				lowerCAmelCase__		  =  accelerator.prepare(snake_case__					)

				return dl







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__    ,			snake_case__    ,			snake_case__    ,			)	->     Tuple:



				"""simple docstring"""





				lowerCAmelCase__		  =  create_dataloader(accelerator=snake_case__    ,			dataset_size=snake_case__    ,			batch_size=snake_case__					)

				lowerCAmelCase__		  =  [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     UpperCAmelCase_		(					)	->     Tuple:



				"""simple docstring"""





				lowerCAmelCase__		  =  create_accelerator()

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







def     UpperCAmelCase_		(					)	->     Optional[Any]:



				"""simple docstring"""





				lowerCAmelCase__		  =  create_accelerator(even_batches=snake_case__					)

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

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







def     UpperCAmelCase_		(					)	->     Tuple:



				"""simple docstring"""





				lowerCAmelCase__		  =  create_accelerator(even_batches=snake_case__					)

				lowerCAmelCase__		  =  torch.nn.Linear(1    ,			1					)
				lowerCAmelCase__		  =  accelerator.prepare(snake_case__					)

				lowerCAmelCase__		  =  create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1					)

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

				accelerator.wait_for_everyone()

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







def     UpperCAmelCase_		(					snake_case__					)	->     Tuple:



				"""simple docstring"""





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

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







def     UpperCAmelCase_		(					)	->     List[str]:



				"""simple docstring"""





				lowerCAmelCase__		  =  True
				lowerCAmelCase__		  =  False
				lowerCAmelCase__		  =  create_accelerator(even_batches=snake_case__					)
				lowerCAmelCase__		  =  torch.nn.Linear(1    ,			1					)
				lowerCAmelCase__		  =  accelerator.prepare(snake_case__					)
				lowerCAmelCase__		  =  create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1					)
				lowerCAmelCase__		  =  create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1					)

				with accelerator.join_uneven_inputs([ddp_model]    ,			even_batches=snake_case__					):
								lowerCAmelCase__		  =  train_dl.batch_sampler.even_batches
								lowerCAmelCase__		  =  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     UpperCAmelCase_		(					)	->     Dict:



				"""simple docstring"""





				lowerCAmelCase__		  =  True
				lowerCAmelCase__		  =  False
				lowerCAmelCase__		  =  create_accelerator(even_batches=snake_case__					)
				lowerCAmelCase__		  =  torch.nn.Linear(1    ,			1					)
				lowerCAmelCase__		  =  accelerator.prepare(snake_case__					)
				create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1    ,			iterable=snake_case__					)
				lowerCAmelCase__		  =  create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1					)

				with warnings.catch_warnings():
								warnings.filterwarnings('ignore'					)
								try:
												with accelerator.join_uneven_inputs([ddp_model]    ,			even_batches=snake_case__					):
																lowerCAmelCase__		  =  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     UpperCAmelCase_		(					)	->     Optional[int]:



				"""simple docstring"""





				lowerCAmelCase__		  =  create_accelerator()
				lowerCAmelCase__		  =  torch.nn.Linear(1    ,			1					)
				lowerCAmelCase__		  =  accelerator.prepare(snake_case__					)
				create_dataloader(snake_case__    ,			dataset_size=3    ,			batch_size=1    ,			iterable=snake_case__					)

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

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







def     UpperCAmelCase_		(					)	->     Optional[Any]:



				"""simple docstring"""





				lowerCAmelCase__		  =  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'					)
				lowerCAmelCase__		  =  accelerator.state.distributed_type
				lowerCAmelCase__		  =  DistributedType.FSDP
				test_join_raises_warning_for_non_ddp_distributed(snake_case__					)
				lowerCAmelCase__		  =  original_state


if __name__ == "__main__":
	main()





import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


_lowerCAmelCase	:   Any    =   datasets.utils.logging.get_logger(__name__)

_lowerCAmelCase	:   Any    =   ["names", "prefix"]
_lowerCAmelCase	:   str    =   ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"]
_lowerCAmelCase	:   List[str]    =   ["encoding_errors", "on_bad_lines"]
_lowerCAmelCase	:   int    =   ["date_format"]


@dataclass
class 	__snake_case   ( datasets.BuilderConfig ):
		SCREAMING_SNAKE_CASE__								=	","
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	"infer"
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	False
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	False
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	"."
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	'"'
		SCREAMING_SNAKE_CASE__								=	0
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	0
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	False
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	10000
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	"strict"
		SCREAMING_SNAKE_CASE__								=	"error"
		SCREAMING_SNAKE_CASE__								=	None
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						if self.delimiter is not None:
										lowerCAmelCase__		  =  self.delimiter
						if self.column_names is not None:
										lowerCAmelCase__		  =  self.column_names



		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  {
						    'sep': self.sep,
						    'header': self.header,
						    'names': self.names,
						    'index_col': self.index_col,
						    'usecols': self.usecols,
						    'prefix': self.prefix,
						    'mangle_dupe_cols': self.mangle_dupe_cols,
						    'engine': self.engine,
						    'converters': self.converters,
						    'true_values': self.true_values,
						    'false_values': self.false_values,
						    'skipinitialspace': self.skipinitialspace,
						    'skiprows': self.skiprows,
						    'nrows': self.nrows,
						    'na_values': self.na_values,
						    'keep_default_na': self.keep_default_na,
						    'na_filter': self.na_filter,
						    'verbose': self.verbose,
						    'skip_blank_lines': self.skip_blank_lines,
						    'thousands': self.thousands,
						    'decimal': self.decimal,
						    'lineterminator': self.lineterminator,
						    'quotechar': self.quotechar,
						    'quoting': self.quoting,
						    'escapechar': self.escapechar,
						    'comment': self.comment,
						    'encoding': self.encoding,
						    'dialect': self.dialect,
						    'error_bad_lines': self.error_bad_lines,
						    'warn_bad_lines': self.warn_bad_lines,
						    'skipfooter': self.skipfooter,
						    'doublequote': self.doublequote,
						    'memory_map': self.memory_map,
						    'float_precision': self.float_precision,
						    'chunksize': self.chunksize,
						    'encoding_errors': self.encoding_errors,
						    'on_bad_lines': self.on_bad_lines,
						    'date_format': self.date_format,
						}

						# some kwargs must not be passed if they don't have a default value
						# some others are deprecated and we can also not pass them if they are the default value
						for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
										if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()    ,a_						):
														del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
						if not (datasets.config.PANDAS_VERSION.major >= 2):
										for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
														del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
						if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
										for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
														del pd_read_csv_kwargs[pd_read_csv_parameter]

						return pd_read_csv_kwargs



class 	__snake_case   ( datasets.ArrowBasedBuilder ):
		SCREAMING_SNAKE_CASE__								=	CsvConfig
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return datasets.DatasetInfo(features=self.config.features						)
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if not self.config.data_files:
										raise ValueError(f'At least one data file must be specified, but got data_files={self.config.data_files}'						)
						lowerCAmelCase__		  =  dl_manager.download_and_extract(self.config.data_files						)
						if isinstance(a_    ,(str, list, tuple)						):
										lowerCAmelCase__		  =  data_files
										if isinstance(a_    ,a_						):
														lowerCAmelCase__		  =  [files]
										lowerCAmelCase__		  =  [dl_manager.iter_files(a_						) for file in files]
										return [datasets.SplitGenerator(name=datasets.Split.TRAIN    ,gen_kwargs={'files': files}						)]
						lowerCAmelCase__		  =  []
						for split_name, files in data_files.items():
										if isinstance(a_    ,a_						):
														lowerCAmelCase__		  =  [files]
										lowerCAmelCase__		  =  [dl_manager.iter_files(a_						) for file in files]
										splits.append(datasets.SplitGenerator(name=a_    ,gen_kwargs={'files': files}						)						)
						return splits
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if self.config.features is not None:
										lowerCAmelCase__		  =  self.config.features.arrow_schema
										if all(not require_storage_cast(a_						) for feature in self.config.features.values()						):
														# cheaper cast
														lowerCAmelCase__		  =  pa.Table.from_arrays([pa_table[field.name] for field in schema]    ,schema=a_						)
										else:
														# more expensive cast; allows str <-> int/float or str to Audio for example
														lowerCAmelCase__		  =  table_cast(a_    ,a_						)
						return pa_table



		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  self.config.features.arrow_schema if self.config.features else None
						# dtype allows reading an int column as str
						lowerCAmelCase__		  =  (
						    {
						        name: dtype.to_pandas_dtype() if not require_storage_cast(a_						) else object
						        for name, dtype, feature in zip(schema.names    ,schema.types    ,self.config.features.values()						)
						    }
						    if schema is not None
						    else None
						)
						for file_idx, file in enumerate(itertools.chain.from_iterable(a_						)						):
										lowerCAmelCase__		  =  pd.read_csv(a_    ,iterator=a_    ,dtype=a_    ,**self.config.pd_read_csv_kwargs						)
										try:
														for batch_idx, df in enumerate(a_						):
																		lowerCAmelCase__		  =  pa.Table.from_pandas(a_						)
																		# Uncomment for debugging (will print the Arrow table size and elements)
																		# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																		# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																		yield (file_idx, batch_idx), self._cast_table(a_						)
										except ValueError as e:
														logger.error(f'Failed to read file \'{file}\' with error {type(a_						)}: {e}'						)
														raise
