


# 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    UpperCAmelCase_	(							_a):
       '''simple docstring'''






       def __init__(     self ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	Tuple   	=		data






       def __iter__(     self						):




              """simple docstring"""




              for element in self.data:
                     yield element




def      a	(							SCREAMING_SNAKE_CASE_      :		int=True       ):






       """simple docstring"""





       UpperCamelCase    :	str   	=		Accelerator(even_batches=SCREAMING_SNAKE_CASE_       )
       assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
       return accelerator


def      a	(							SCREAMING_SNAKE_CASE_      :		Accelerator							,			SCREAMING_SNAKE_CASE_      :		int							,			SCREAMING_SNAKE_CASE_      :		int							,			SCREAMING_SNAKE_CASE_      :		bool = False       ):






       """simple docstring"""





       if iterable:
              UpperCamelCase    :	Any   	=		DummyIterableDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE_       )       )       )
       else:
              UpperCamelCase    :	Any   	=		TensorDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE_       )       )       )

       UpperCamelCase    :	Union[str, Any]   	=		DataLoader(SCREAMING_SNAKE_CASE_							,			batch_size=SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	List[str]   	=		accelerator.prepare(SCREAMING_SNAKE_CASE_       )

       return dl


def      a	(							SCREAMING_SNAKE_CASE_      :		Accelerator							,			SCREAMING_SNAKE_CASE_      :		int							,			SCREAMING_SNAKE_CASE_      :		int							,			SCREAMING_SNAKE_CASE_      :		List[int]							,			SCREAMING_SNAKE_CASE_      :		List[int]							,			):






       """simple docstring"""





       UpperCamelCase    :	List[Any]   	=		create_dataloader(accelerator=SCREAMING_SNAKE_CASE_							,			dataset_size=SCREAMING_SNAKE_CASE_							,			batch_size=SCREAMING_SNAKE_CASE_       )

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






       """simple docstring"""





       UpperCamelCase    :	Any   	=		create_accelerator()

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


def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	str   	=		create_accelerator(even_batches=SCREAMING_SNAKE_CASE_       )

       verify_dataloader_batch_sizes(
           SCREAMING_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(
           SCREAMING_SNAKE_CASE_							,			dataset_size=7							,			batch_size=2							,			process_0_expected_batch_sizes=[2, 2]							,			process_1_expected_batch_sizes=[2, 1]							,			)


def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	Union[str, Any]   	=		create_accelerator(even_batches=SCREAMING_SNAKE_CASE_       )

       UpperCamelCase    :	int   	=		torch.nn.Linear(1							,			1       )
       UpperCamelCase    :	str   	=		accelerator.prepare(SCREAMING_SNAKE_CASE_       )

       UpperCamelCase    :	Dict   	=		create_dataloader(SCREAMING_SNAKE_CASE_							,			dataset_size=3							,			batch_size=1       )

       UpperCamelCase    :	int   	=		[]
       with accelerator.join_uneven_inputs([ddp_model]       ):
              for batch_idx, batch in enumerate(SCREAMING_SNAKE_CASE_       ):
                     UpperCamelCase    :	Union[str, Any]   	=		ddp_model(batch[0].float()       )
                     UpperCamelCase    :	Dict   	=		output.sum()
                     loss.backward()
                     batch_idxs.append(SCREAMING_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      a	(							SCREAMING_SNAKE_CASE_      :		Union[str, Any]       ):






       """simple docstring"""





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

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


def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	Any   	=		True
       UpperCamelCase    :	Union[str, Any]   	=		False
       UpperCamelCase    :	Optional[Any]   	=		create_accelerator(even_batches=SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	Optional[Any]   	=		torch.nn.Linear(1							,			1       )
       UpperCamelCase    :	Optional[Any]   	=		accelerator.prepare(SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	Union[str, Any]   	=		create_dataloader(SCREAMING_SNAKE_CASE_							,			dataset_size=3							,			batch_size=1       )
       UpperCamelCase    :	str   	=		create_dataloader(SCREAMING_SNAKE_CASE_							,			dataset_size=3							,			batch_size=1       )

       with accelerator.join_uneven_inputs([ddp_model]							,			even_batches=SCREAMING_SNAKE_CASE_       ):
              UpperCamelCase    :	Any   	=		train_dl.batch_sampler.even_batches
              UpperCamelCase    :	List[str]   	=		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	(							):






       """simple docstring"""





       UpperCamelCase    :	List[str]   	=		True
       UpperCamelCase    :	str   	=		False
       UpperCamelCase    :	Optional[Any]   	=		create_accelerator(even_batches=SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	List[str]   	=		torch.nn.Linear(1							,			1       )
       UpperCamelCase    :	Any   	=		accelerator.prepare(SCREAMING_SNAKE_CASE_       )
       create_dataloader(SCREAMING_SNAKE_CASE_							,			dataset_size=3							,			batch_size=1							,			iterable=SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	Tuple   	=		create_dataloader(SCREAMING_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=SCREAMING_SNAKE_CASE_       ):
                            UpperCamelCase    :	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      a	(							):






       """simple docstring"""





       UpperCamelCase    :	Optional[Any]   	=		create_accelerator()
       UpperCamelCase    :	List[str]   	=		torch.nn.Linear(1							,			1       )
       UpperCamelCase    :	Dict   	=		accelerator.prepare(SCREAMING_SNAKE_CASE_       )
       create_dataloader(SCREAMING_SNAKE_CASE_							,			dataset_size=3							,			batch_size=1							,			iterable=SCREAMING_SNAKE_CASE_       )

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

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


def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	Optional[int]   	=		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    :	Tuple   	=		accelerator.state.distributed_type
       UpperCamelCase    :	Optional[Any]   	=		DistributedType.FSDP
       test_join_raises_warning_for_non_ddp_distributed(SCREAMING_SNAKE_CASE_       )
       UpperCamelCase    :	List[Any]   	=		original_state


if __name__ == "__main__":
  main()





import copy
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


__UpperCAmelCase : Optional[Any] 			=				logging.get_logger(__name__)

__UpperCAmelCase : List[str] 			=				{
    "microsoft/conditional-detr-resnet-50": (
        "https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json"
    ),
}



class    UpperCAmelCase_	(							_a):
       '''simple docstring'''
       __UpperCamelCase      :     Optional[int]							=					"conditional_detr"
       __UpperCamelCase      :     Optional[Any]							=					["past_key_values"]
       __UpperCamelCase      :     Union[str, Any]							=					{
           "hidden_size": "d_model",
           "num_attention_heads": "encoder_attention_heads",
       }






       def __init__(     self ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=None ,					__SCREAMING_SNAKE_CASE=3 ,					__SCREAMING_SNAKE_CASE=300 ,					__SCREAMING_SNAKE_CASE=6 ,					__SCREAMING_SNAKE_CASE=2_048 ,					__SCREAMING_SNAKE_CASE=8 ,					__SCREAMING_SNAKE_CASE=6 ,					__SCREAMING_SNAKE_CASE=2_048 ,					__SCREAMING_SNAKE_CASE=8 ,					__SCREAMING_SNAKE_CASE=0.0 ,					__SCREAMING_SNAKE_CASE=0.0 ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE="relu" ,					__SCREAMING_SNAKE_CASE=256 ,					__SCREAMING_SNAKE_CASE=0.1 ,					__SCREAMING_SNAKE_CASE=0.0 ,					__SCREAMING_SNAKE_CASE=0.0 ,					__SCREAMING_SNAKE_CASE=0.02 ,					__SCREAMING_SNAKE_CASE=1.0 ,					__SCREAMING_SNAKE_CASE=False ,					__SCREAMING_SNAKE_CASE="sine" ,					__SCREAMING_SNAKE_CASE="resnet50" ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=False ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=5 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=1 ,					__SCREAMING_SNAKE_CASE=1 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=5 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=0.25 ,					**__SCREAMING_SNAKE_CASE ,					):




              """simple docstring"""




              if backbone_config is not None and use_timm_backbone:
                     raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''						)

              if not use_timm_backbone:
                     if backbone_config is None:
                            logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''						)
                            UpperCamelCase    :	str   	=		CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']						)
                     elif isinstance(__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):
                            UpperCamelCase    :	Tuple   	=		backbone_config.get('''model_type'''						)
                            UpperCamelCase    :	Optional[Any]   	=		CONFIG_MAPPING[backbone_model_type]
                            UpperCamelCase    :	Any   	=		config_class.from_dict(__SCREAMING_SNAKE_CASE						)

              UpperCamelCase    :	List[str]   	=		use_timm_backbone
              UpperCamelCase    :	int   	=		backbone_config
              UpperCamelCase    :	Any   	=		num_channels
              UpperCamelCase    :	Optional[Any]   	=		num_queries
              UpperCamelCase    :	Tuple   	=		d_model
              UpperCamelCase    :	Optional[Any]   	=		encoder_ffn_dim
              UpperCamelCase    :	Optional[int]   	=		encoder_layers
              UpperCamelCase    :	Union[str, Any]   	=		encoder_attention_heads
              UpperCamelCase    :	Optional[Any]   	=		decoder_ffn_dim
              UpperCamelCase    :	Optional[int]   	=		decoder_layers
              UpperCamelCase    :	Optional[Any]   	=		decoder_attention_heads
              UpperCamelCase    :	Any   	=		dropout
              UpperCamelCase    :	List[Any]   	=		attention_dropout
              UpperCamelCase    :	List[Any]   	=		activation_dropout
              UpperCamelCase    :	List[str]   	=		activation_function
              UpperCamelCase    :	Optional[int]   	=		init_std
              UpperCamelCase    :	Optional[Any]   	=		init_xavier_std
              UpperCamelCase    :	Union[str, Any]   	=		encoder_layerdrop
              UpperCamelCase    :	Optional[Any]   	=		decoder_layerdrop
              UpperCamelCase    :	Tuple   	=		encoder_layers
              UpperCamelCase    :	Optional[Any]   	=		auxiliary_loss
              UpperCamelCase    :	Union[str, Any]   	=		position_embedding_type
              UpperCamelCase    :	Optional[int]   	=		backbone
              UpperCamelCase    :	Dict   	=		use_pretrained_backbone
              UpperCamelCase    :	Tuple   	=		dilation
              # Hungarian matcher
              UpperCamelCase    :	Union[str, Any]   	=		class_cost
              UpperCamelCase    :	List[Any]   	=		bbox_cost
              UpperCamelCase    :	Optional[Any]   	=		giou_cost
              # Loss coefficients
              UpperCamelCase    :	Optional[Any]   	=		mask_loss_coefficient
              UpperCamelCase    :	Optional[int]   	=		dice_loss_coefficient
              UpperCamelCase    :	Optional[Any]   	=		cls_loss_coefficient
              UpperCamelCase    :	Optional[int]   	=		bbox_loss_coefficient
              UpperCamelCase    :	Optional[int]   	=		giou_loss_coefficient
              UpperCamelCase    :	Optional[int]   	=		focal_alpha
              super().__init__(is_encoder_decoder=__SCREAMING_SNAKE_CASE ,					**__SCREAMING_SNAKE_CASE						)






       @property
       def  _lowercase   (     self						):




              """simple docstring"""




              return self.encoder_attention_heads






       @property
       def  _lowercase   (     self						):




              """simple docstring"""




              return self.d_model






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	Union[str, Any]   	=		copy.deepcopy(self.__dict__						)
              if self.backbone_config is not None:
                     UpperCamelCase    :	List[Any]   	=		self.backbone_config.to_dict()
              UpperCamelCase    :	List[Any]   	=		self.__class__.model_type
              return output




class    UpperCAmelCase_	(							_a):
       '''simple docstring'''
       __UpperCamelCase      :     Dict							=					version.parse("1.11")






       @property
       def  _lowercase   (     self						):




              """simple docstring"""




              return OrderedDict(
                  [
                      ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                      ('''pixel_mask''', {0: '''batch'''}),
                  ]						)






       @property
       def  _lowercase   (     self						):




              """simple docstring"""




              return 1e-5






       @property
       def  _lowercase   (     self						):




              """simple docstring"""




              return 12

