






# 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_	):
							def __init__(     self:      Tuple       ,	UpperCamelCase:      Optional[int]						)		->		Union[str, Any]:
											snake_case__									=     data


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


def      a_ (      _A=True  )			->			Optional[Any]:







				"""simple docstring"""
				snake_case__									=     Accelerator(even_batches=_A  )
				assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
				return accelerator
def      a_ (      _A      ,   _A      ,   _A      ,   _A = False  )			->			int:







				"""simple docstring"""
				if iterable:
								snake_case__									=     DummyIterableDataset(torch.as_tensor(range(_A  )  )  )
				else:
								snake_case__									=     TensorDataset(torch.as_tensor(range(_A  )  )  )

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

				return dl
def      a_ (      _A      ,   _A      ,   _A      ,   _A      ,   _A      ,   )			->			Optional[Any]:







				"""simple docstring"""
				snake_case__									=     create_dataloader(accelerator=_A      ,   dataset_size=_A      ,   batch_size=_A  )

				snake_case__									=     [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      a_ (      )			->			int:







				"""simple docstring"""
				snake_case__									=     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      a_ (      )			->			str:







				"""simple docstring"""
				snake_case__									=     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      a_ (      )			->			int:







				"""simple docstring"""
				snake_case__									=     create_accelerator(even_batches=_A  )

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

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

				snake_case__									=     []
				with accelerator.join_uneven_inputs([ddp_model]  ):
								for batch_idx, batch in enumerate(_A  ):
												snake_case__									=     ddp_model(batch[0].float()  )
												snake_case__									=     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      a_ (      _A  )			->			Dict:







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







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

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







				"""simple docstring"""
				snake_case__									=     True
				snake_case__									=     False
				snake_case__									=     create_accelerator(even_batches=_A  )
				snake_case__									=     torch.nn.Linear(1      ,   1  )
				snake_case__									=     accelerator.prepare(_A  )
				create_dataloader(_A      ,   dataset_size=3      ,   batch_size=1      ,   iterable=_A  )
				snake_case__									=     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  ):
																snake_case__									=     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      a_ (      )			->			Dict:







				"""simple docstring"""
				snake_case__									=     create_accelerator()
				snake_case__									=     torch.nn.Linear(1      ,   1  )
				snake_case__									=     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      a_ (      )			->			str:







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


if __name__ == "__main__":
							main()












import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor


class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							def __init__(     self:      List[str]       ,	UpperCamelCase:      Dict       ,	UpperCamelCase:      Optional[int]=3       ,	UpperCamelCase:      Union[str, Any]=32       ,	UpperCamelCase:      Optional[int]=3       ,	UpperCamelCase:      Any=10       ,	UpperCamelCase:      List[str]=[10, 20, 30, 40]       ,	UpperCamelCase:      Optional[Any]=[1, 1, 2, 1]       ,	UpperCamelCase:      Tuple=True       ,	UpperCamelCase:      List[str]=True       ,	UpperCamelCase:      Optional[int]="relu"       ,	UpperCamelCase:      List[str]=3       ,	UpperCamelCase:      Dict=None       ,	)		->		Optional[Any]:
											snake_case__									=     parent
											snake_case__									=     batch_size
											snake_case__									=     image_size
											snake_case__									=     num_channels
											snake_case__									=     embeddings_size
											snake_case__									=     hidden_sizes
											snake_case__									=     depths
											snake_case__									=     is_training
											snake_case__									=     use_labels
											snake_case__									=     hidden_act
											snake_case__									=     num_labels
											snake_case__									=     scope
											snake_case__									=     len(UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		Dict:
											snake_case__									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

											snake_case__									=     self.get_config()

											return config, pixel_values
							def lowerCAmelCase_ (     self:      int						)		->		Optional[Any]:
											return RegNetConfig(
											    num_channels=self.num_channels       ,	embeddings_size=self.embeddings_size       ,	hidden_sizes=self.hidden_sizes       ,	depths=self.depths       ,	hidden_act=self.hidden_act       ,	num_labels=self.num_labels       ,	image_size=self.image_size       ,	)
							def lowerCAmelCase_ (     self:      Optional[Any]       ,	UpperCamelCase:      List[Any]       ,	UpperCamelCase:      List[Any]						)		->		Optional[Any]:
											snake_case__									=     FlaxRegNetModel(config=UpperCamelCase						)
											snake_case__									=     model(UpperCamelCase						)

											# Output shape (b, c, h, w)
											self.parent.assertEqual(
											    result.last_hidden_state.shape       ,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,	)
							def lowerCAmelCase_ (     self:      List[str]       ,	UpperCamelCase:      Tuple       ,	UpperCamelCase:      Optional[Any]						)		->		List[str]:
											snake_case__									=     self.num_labels
											snake_case__									=     FlaxRegNetForImageClassification(config=UpperCamelCase						)
											snake_case__									=     model(UpperCamelCase						)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels)						)


							def lowerCAmelCase_ (     self:      Tuple						)		->		List[str]:
											snake_case__									=     self.prepare_config_and_inputs()
											snake_case__							,						snake_case__									=     config_and_inputs
											snake_case__									=     {'pixel_values': pixel_values}
											return config, inputs_dict


@require_flax
class   __SCREAMING_SNAKE_CASE(	a_    ,  unittest.TestCase	):
							_UpperCAmelCase     =       (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       False
							def lowerCAmelCase_ (     self:      Dict						)		->		None:
											snake_case__									=     FlaxRegNetModelTester(self						)
											snake_case__									=     ConfigTester(self       ,	config_class=UpperCamelCase       ,	has_text_modality=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      str						)		->		Optional[int]:
											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()
							def lowerCAmelCase_ (     self:      List[Any]						)		->		List[str]:
											return
							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		Union[str, Any]:
											snake_case__									=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Tuple						)		->		List[Any]:
											snake_case__									=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*UpperCamelCase						)
							@unittest.skip(reason='RegNet does not use inputs_embeds'						)
							def lowerCAmelCase_ (     self:      Optional[Any]						)		->		Dict:
											pass
							@unittest.skip(reason='RegNet does not support input and output embeddings'						)
							def lowerCAmelCase_ (     self:      List[str]						)		->		Dict:
											pass
							def lowerCAmelCase_ (     self:      Tuple						)		->		int:
											snake_case__							,						snake_case__									=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															snake_case__									=     model_class(UpperCamelCase						)
															snake_case__									=     inspect.signature(model.__call__						)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															snake_case__									=     [*signature.parameters.keys()]

															snake_case__									=     ['pixel_values']
															self.assertListEqual(arg_names[:1]       ,	UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		int:
											def check_hidden_states_output(UpperCamelCase:      Optional[int]       ,	UpperCamelCase:      Optional[Any]       ,	UpperCamelCase:      List[Any]						):
															snake_case__									=     model_class(UpperCamelCase						)

															snake_case__									=     model(**self._prepare_for_class(UpperCamelCase       ,	UpperCamelCase						)						)

															snake_case__									=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															snake_case__									=     self.model_tester.num_stages
															self.assertEqual(len(UpperCamelCase						)       ,	expected_num_stages + 1						)

											snake_case__							,						snake_case__									=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															snake_case__									=     True
															check_hidden_states_output(UpperCamelCase       ,	UpperCamelCase       ,	UpperCamelCase						)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															snake_case__									=     True

															check_hidden_states_output(UpperCamelCase       ,	UpperCamelCase       ,	UpperCamelCase						)


							def lowerCAmelCase_ (     self:      str						)		->		str:
											snake_case__							,						snake_case__									=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__						):
																			snake_case__									=     self._prepare_for_class(UpperCamelCase       ,	UpperCamelCase						)
																			snake_case__									=     model_class(UpperCamelCase						)

																			@jax.jit
																			def model_jitted(UpperCamelCase:      str       ,	**UpperCamelCase:      Tuple						):
																							return model(pixel_values=UpperCamelCase       ,	**UpperCamelCase						)

																			with self.subTest('JIT Enabled'						):
																							snake_case__									=     model_jitted(**UpperCamelCase						).to_tuple()

																			with self.subTest('JIT Disabled'						):
																							with jax.disable_jit():
																											snake_case__									=     model_jitted(**UpperCamelCase						).to_tuple()

																			self.assertEqual(len(UpperCamelCase						)       ,	len(UpperCamelCase						)						)
																			for jitted_output, output in zip(UpperCamelCase       ,	UpperCamelCase						):
																							self.assertEqual(jitted_output.shape       ,	output.shape						)


def      a_ (      )			->			Optional[int]:







				"""simple docstring"""
				snake_case__									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
				return image


@require_flax
class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							@cached_property
							def lowerCAmelCase_ (     self:      str						)		->		Any:
											return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'						) if is_vision_available() else None


							@slow
							def lowerCAmelCase_ (     self:      List[str]						)		->		Optional[Any]:
											snake_case__									=     FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'						)

											snake_case__									=     self.default_image_processor
											snake_case__									=     prepare_img()
											snake_case__									=     image_processor(images=UpperCamelCase       ,	return_tensors='np'						)

											snake_case__									=     model(**UpperCamelCase						)

											# verify the logits
											snake_case__									=     (1, 10_00)
											self.assertEqual(outputs.logits.shape       ,	UpperCamelCase						)

											snake_case__									=     jnp.array([-0.4_180, -1.5_051, -3.4_836]						)

											self.assertTrue(jnp.allclose(outputs.logits[0, :3]       ,	UpperCamelCase       ,	atol=1e-4						)						)




