



'''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 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(							A__			):







	"""simple docstring"""






	def __init__(						self			:     Union[str, Any]		,			__snake_case			:     Optional[int]		)			->		List[str]:
								UpperCAmelCase :       str 							=		data







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


def  snake_case_     (					_lowerCAmelCase  :						str=True  )      ->   List[str]:
							UpperCAmelCase :       Optional[int] 							=		Accelerator(even_batches=_lowerCAmelCase  )
							assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
							return accelerator


def  snake_case_     (					_lowerCAmelCase  :						Accelerator   ,      _lowerCAmelCase  :						int   ,      _lowerCAmelCase  :						int   ,      _lowerCAmelCase  :						bool = False  )      ->   List[Any]:
							if iterable:
														UpperCAmelCase :       Any 							=		DummyIterableDataset(torch.as_tensor(range(_lowerCAmelCase  )  )  )
							else:
														UpperCAmelCase :       Union[str, Any] 							=		TensorDataset(torch.as_tensor(range(_lowerCAmelCase  )  )  )

							UpperCAmelCase :       Tuple 							=		DataLoader(_lowerCAmelCase   ,      batch_size=_lowerCAmelCase  )
							UpperCAmelCase :       List[str] 							=		accelerator.prepare(_lowerCAmelCase  )

							return dl


def  snake_case_     (					_lowerCAmelCase  :						Accelerator   ,      _lowerCAmelCase  :						int   ,      _lowerCAmelCase  :						int   ,      _lowerCAmelCase  :						List[int]   ,      _lowerCAmelCase  :						List[int]   ,      )      ->   Optional[int]:
							UpperCAmelCase :       Optional[Any] 							=		create_dataloader(accelerator=_lowerCAmelCase   ,      dataset_size=_lowerCAmelCase   ,      batch_size=_lowerCAmelCase  )

							UpperCAmelCase :       int 							=		[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_     (					)      ->   Union[str, Any]:
							UpperCAmelCase :       Dict 							=		create_accelerator()

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


def  snake_case_     (					)      ->   Dict:
							UpperCAmelCase :       Tuple 							=		create_accelerator(even_batches=_lowerCAmelCase  )

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

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


def  snake_case_     (					)      ->   Tuple:
							UpperCAmelCase :       Union[str, Any] 							=		create_accelerator(even_batches=_lowerCAmelCase  )

							UpperCAmelCase :       int 							=		torch.nn.Linear(1   ,      1  )
							UpperCAmelCase :       Any 							=		accelerator.prepare(_lowerCAmelCase  )

							UpperCAmelCase :       Optional[int] 							=		create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1  )

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

							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_     (					_lowerCAmelCase  :						Optional[int]  )      ->   List[str]:
							with warnings.catch_warnings(record=_lowerCAmelCase  ) as w:
														with accelerator.join_uneven_inputs([Mock()]  ):
																					pass

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


def  snake_case_     (					)      ->   Dict:
							UpperCAmelCase :       Dict 							=		True
							UpperCAmelCase :       Optional[int] 							=		False
							UpperCAmelCase :       Tuple 							=		create_accelerator(even_batches=_lowerCAmelCase  )
							UpperCAmelCase :       Union[str, Any] 							=		torch.nn.Linear(1   ,      1  )
							UpperCAmelCase :       List[str] 							=		accelerator.prepare(_lowerCAmelCase  )
							UpperCAmelCase :       str 							=		create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1  )
							UpperCAmelCase :       Any 							=		create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1  )

							with accelerator.join_uneven_inputs([ddp_model]   ,      even_batches=_lowerCAmelCase  ):
														UpperCAmelCase :       Tuple 							=		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_     (					)      ->   Dict:
							UpperCAmelCase :       List[Any] 							=		True
							UpperCAmelCase :       List[Any] 							=		False
							UpperCAmelCase :       Tuple 							=		create_accelerator(even_batches=_lowerCAmelCase  )
							UpperCAmelCase :       List[str] 							=		torch.nn.Linear(1   ,      1  )
							UpperCAmelCase :       List[Any] 							=		accelerator.prepare(_lowerCAmelCase  )
							create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1   ,      iterable=_lowerCAmelCase  )
							UpperCAmelCase :       int 							=		create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1  )

							with warnings.catch_warnings():
														warnings.filterwarnings('''ignore'''  )
														try:
																					with accelerator.join_uneven_inputs([ddp_model]   ,      even_batches=_lowerCAmelCase  ):
																												UpperCAmelCase :       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  snake_case_     (					)      ->   Dict:
							UpperCAmelCase :       Tuple 							=		create_accelerator()
							UpperCAmelCase :       Any 							=		torch.nn.Linear(1   ,      1  )
							UpperCAmelCase :       Dict 							=		accelerator.prepare(_lowerCAmelCase  )
							create_dataloader(_lowerCAmelCase   ,      dataset_size=3   ,      batch_size=1   ,      iterable=_lowerCAmelCase  )

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

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


def  snake_case_     (					)      ->   Optional[int]:
							UpperCAmelCase :       str 							=		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 :       str 							=		accelerator.state.distributed_type
							UpperCAmelCase :       str 							=		DistributedType.FSDP
							test_join_raises_warning_for_non_ddp_distributed(_lowerCAmelCase  )
							UpperCAmelCase :       Optional[Any] 							=		original_state


if __name__ == "__main__":
						main()










'''simple docstring'''






import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
						import os

						from flax.core.frozen_dict import unfreeze
						from flax.traverse_util import flatten_dict

						from transformers import FlaxBertModel

						UpperCamelCase__:   Tuple								=			"0.12"  # assumed parallelism: 8

@require_flax
@is_staging_test
class 				SCREAMING_SNAKE_CASE(							unittest.TestCase			):







	"""simple docstring"""






	@classmethod
	def      A	(						cls			:     Union[str, Any]		)			->		int:
								UpperCAmelCase :       Optional[Any] 							=		TOKEN
								HfFolder.save_token(__snake_case		)







	@classmethod
	def      A	(						cls			:     List[str]		)			->		Tuple:
								try:
															delete_repo(token=cls._token		,			repo_id='''test-model-flax'''		)
								except HTTPError:
															pass

								try:
															delete_repo(token=cls._token		,			repo_id='''valid_org/test-model-flax-org'''		)
								except HTTPError:
															pass







	def      A	(						self			:     int		)			->		Tuple:
								UpperCAmelCase :       List[Any] 							=		BertConfig(
								    vocab_size=99		,			hidden_size=32		,			num_hidden_layers=5		,			num_attention_heads=4		,			intermediate_size=37		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)
								model.push_to_hub('''test-model-flax'''		,			use_auth_token=self._token		)

								UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""		)

								UpperCAmelCase :       List[Any] 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       Tuple 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Union[str, Any] 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)

								# Reset repo
								delete_repo(token=self._token		,			repo_id='''test-model-flax'''		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(__snake_case		,			repo_id='''test-model-flax'''		,			push_to_hub=__snake_case		,			use_auth_token=self._token		)

								UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""		)

								UpperCAmelCase :       Any 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       str 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Optional[Any] 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)







	def      A	(						self			:     Optional[Any]		)			->		Union[str, Any]:
								UpperCAmelCase :       Dict 							=		BertConfig(
								    vocab_size=99		,			hidden_size=32		,			num_hidden_layers=5		,			num_attention_heads=4		,			intermediate_size=37		)
								UpperCAmelCase :       Optional[Any] 							=		FlaxBertModel(__snake_case		)
								model.push_to_hub('''valid_org/test-model-flax-org'''		,			use_auth_token=self._token		)

								UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''		)

								UpperCAmelCase :       List[Any] 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       int 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Any 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)

								# Reset repo
								delete_repo(token=self._token		,			repo_id='''valid_org/test-model-flax-org'''		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(
															    __snake_case		,			repo_id='''valid_org/test-model-flax-org'''		,			push_to_hub=__snake_case		,			use_auth_token=self._token		)

								UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''		)

								UpperCAmelCase :       Any 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       Optional[Any] 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       int 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)


def  snake_case_     (					_lowerCAmelCase  :						Optional[Any]   ,      _lowerCAmelCase  :						Any  )      ->   Union[str, Any]:
							UpperCAmelCase :       str 							=		True
							UpperCAmelCase :       int 							=		flatten_dict(modela.params  )
							UpperCAmelCase :       Dict 							=		flatten_dict(modela.params  )
							for key in flat_params_a.keys():
														if np.sum(np.abs(flat_params_a[key] - flat_params_a[key]  )  ) > 1e-4:
																					UpperCAmelCase :       Dict 							=		False

							return models_are_equal




@require_flax
class 				SCREAMING_SNAKE_CASE(							unittest.TestCase			):







	"""simple docstring"""






	def      A	(						self			:     Tuple		)			->		Union[str, Any]:
								UpperCAmelCase :       List[Any] 							=		BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)

								UpperCAmelCase :       int 							=		'''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(os.path.join(__snake_case		,			__snake_case		)		)

															with self.assertRaises(__snake_case		):
																						UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(__snake_case		)

															UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertTrue(check_models_equal(__snake_case		,			__snake_case		)		)







	def      A	(						self			:     List[str]		)			->		Dict:
								UpperCAmelCase :       Dict 							=		BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)

								UpperCAmelCase :       Optional[int] 							=		'''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(os.path.join(__snake_case		,			__snake_case		)		,			max_shard_size='''10KB'''		)

															with self.assertRaises(__snake_case		):
																						UpperCAmelCase :       Any 							=		FlaxBertModel.from_pretrained(__snake_case		)

															UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertTrue(check_models_equal(__snake_case		,			__snake_case		)		)







	def      A	(						self			:     Optional[int]		)			->		str:
								UpperCAmelCase :       Dict 							=		'''bert'''
								UpperCAmelCase :       int 							=		'''hf-internal-testing/tiny-random-bert-subfolder'''

								with self.assertRaises(__snake_case		):
															UpperCAmelCase :       Optional[Any] 							=		FlaxBertModel.from_pretrained(__snake_case		)

								UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertIsNotNone(__snake_case		)







	def      A	(						self			:     Dict		)			->		List[Any]:
								UpperCAmelCase :       Optional[int] 							=		'''bert'''
								UpperCAmelCase :       int 							=		'''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
								with self.assertRaises(__snake_case		):
															UpperCAmelCase :       Dict 							=		FlaxBertModel.from_pretrained(__snake_case		)

								UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertIsNotNone(__snake_case		)





