
# 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   (	UpperCAmelCase_							):


 def __init__(					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Union[str, Any]    		=      data



 def __iter__(					self):


   '''simple docstring'''




   for element in self.data:
     yield element

def 		UpperCamelCase	(      lowercase_=True   )		->	List[str]:


  '''simple docstring'''






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

def 		UpperCamelCase	(      lowercase_ , lowercase_ , lowercase_ , lowercase_ = False   )		->	List[str]:


  '''simple docstring'''






  if iterable:
    lowercase__  :   str    		=      DummyIterableDataset(torch.as_tensor(range(lowercase_   )   )   )
  else:
    lowercase__  :   Optional[int]    		=      TensorDataset(torch.as_tensor(range(lowercase_   )   )   )

  lowercase__  :   int    		=      DataLoader(lowercase_ , batch_size=lowercase_   )
  lowercase__  :   int    		=      accelerator.prepare(lowercase_   )

  return dl

def 		UpperCamelCase	(      lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , )		->	Any:


  '''simple docstring'''






  lowercase__  :   Any    		=      create_dataloader(accelerator=lowercase_ , dataset_size=lowercase_ , batch_size=lowercase_   )

  lowercase__  :   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 		UpperCamelCase	(      )		->	Union[str, Any]:


  '''simple docstring'''






  lowercase__  :   Tuple    		=      create_accelerator()

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

def 		UpperCamelCase	(      )		->	Dict:


  '''simple docstring'''






  lowercase__  :   List[str]    		=      create_accelerator(even_batches=lowercase_   )

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

  verify_dataloader_batch_sizes(
      lowercase_ , 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'''






  lowercase__  :   List[Any]    		=      create_accelerator(even_batches=lowercase_   )

  lowercase__  :   str    		=      torch.nn.Linear(1 , 1   )
  lowercase__  :   Optional[int]    		=      accelerator.prepare(lowercase_   )

  lowercase__  :   Optional[Any]    		=      create_dataloader(lowercase_ , dataset_size=3 , batch_size=1   )

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

  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	(      lowercase_   )		->	Dict:


  '''simple docstring'''






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

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

def 		UpperCamelCase	(      )		->	Optional[Any]:


  '''simple docstring'''






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

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


  '''simple docstring'''






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

  with warnings.catch_warnings():
    warnings.filterwarnings("""ignore"""   )
    try:
      with accelerator.join_uneven_inputs([ddp_model] , even_batches=lowercase_   ):
        lowercase__  :   int    		=      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	(      )		->	str:


  '''simple docstring'''






  lowercase__  :   int    		=      create_accelerator()
  lowercase__  :   Dict    		=      torch.nn.Linear(1 , 1   )
  lowercase__  :   Optional[int]    		=      accelerator.prepare(lowercase_   )
  create_dataloader(lowercase_ , dataset_size=3 , batch_size=1 , iterable=lowercase_   )

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

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

def 		UpperCamelCase	(      )		->	Tuple:


  '''simple docstring'''






  lowercase__  :   List[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"""   )
  lowercase__  :   Dict    		=      accelerator.state.distributed_type
  lowercase__  :   Any    		=      DistributedType.FSDP
  test_join_raises_warning_for_non_ddp_distributed(lowercase_   )
  lowercase__  :   List[Any]    		=      original_state


if __name__ == "__main__":
     main()








import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig


lowerCamelCase__    :		List[str]          =   logging.get_logger(__name__)

lowerCamelCase__    :		str          =   {
    """Intel/dpt-large""": """https://huggingface.co/Intel/dpt-large/resolve/main/config.json""",
    # See all DPT models at https://huggingface.co/models?filter=dpt
}



class       _snake_case   (	UpperCAmelCase_							):
 __lowerCAmelCase  :     Optional[int]        =			'dpt'


 def __init__(					self					,  SCREAMING_SNAKE_CASE_=7_68					,  SCREAMING_SNAKE_CASE_=12					,  SCREAMING_SNAKE_CASE_=12					,  SCREAMING_SNAKE_CASE_=30_72					,  SCREAMING_SNAKE_CASE_="gelu"					,  SCREAMING_SNAKE_CASE_=0.0					,  SCREAMING_SNAKE_CASE_=0.0					,  SCREAMING_SNAKE_CASE_=0.0_2					,  SCREAMING_SNAKE_CASE_=1E-12					,  SCREAMING_SNAKE_CASE_=3_84					,  SCREAMING_SNAKE_CASE_=16					,  SCREAMING_SNAKE_CASE_=3					,  SCREAMING_SNAKE_CASE_=False					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=[2, 5, 8, 11]					,  SCREAMING_SNAKE_CASE_="project"					,  SCREAMING_SNAKE_CASE_=[4, 2, 1, 0.5]					,  SCREAMING_SNAKE_CASE_=[96, 1_92, 3_84, 7_68]					,  SCREAMING_SNAKE_CASE_=2_56					,  SCREAMING_SNAKE_CASE_=-1					,  SCREAMING_SNAKE_CASE_=False					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=0.4					,  SCREAMING_SNAKE_CASE_=2_55					,  SCREAMING_SNAKE_CASE_=0.1					,  SCREAMING_SNAKE_CASE_=[1, 10_24, 24, 24]					,  SCREAMING_SNAKE_CASE_=[0, 1]					,  SCREAMING_SNAKE_CASE_=None					,  **SCREAMING_SNAKE_CASE_					,  ):


   '''simple docstring'''




   super().__init__(**SCREAMING_SNAKE_CASE_)

   lowercase__  :   List[str]    		=      hidden_size
   lowercase__  :   str    		=      is_hybrid

   if self.is_hybrid:
     if backbone_config is None:
       logger.info("""Initializing the config with a `BiT` backbone.""")
       lowercase__  :   Any    		=      {
           """global_padding""": """same""",
           """layer_type""": """bottleneck""",
           """depths""": [3, 4, 9],
           """out_features""": ["""stage1""", """stage2""", """stage3"""],
           """embedding_dynamic_padding""": True,
       }
       lowercase__  :   Optional[Any]    		=      BitConfig(**SCREAMING_SNAKE_CASE_)
     elif isinstance(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):
       logger.info("""Initializing the config with a `BiT` backbone.""")
       lowercase__  :   List[Any]    		=      BitConfig(**SCREAMING_SNAKE_CASE_)
     elif isinstance(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):
       lowercase__  :   int    		=      backbone_config
     else:
       raise ValueError(
           f'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.')

     lowercase__  :   Optional[Any]    		=      backbone_featmap_shape
     lowercase__  :   List[str]    		=      neck_ignore_stages

     if readout_type != "project":
       raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""")
   else:
     lowercase__  :   Optional[int]    		=      None
     lowercase__  :   Union[str, Any]    		=      None
     lowercase__  :   Tuple    		=      []

   lowercase__  :   List[str]    		=      num_hidden_layers
   lowercase__  :   Union[str, Any]    		=      num_attention_heads
   lowercase__  :   List[Any]    		=      intermediate_size
   lowercase__  :   Optional[Any]    		=      hidden_act
   lowercase__  :   int    		=      hidden_dropout_prob
   lowercase__  :   str    		=      attention_probs_dropout_prob
   lowercase__  :   Dict    		=      initializer_range
   lowercase__  :   Tuple    		=      layer_norm_eps
   lowercase__  :   List[str]    		=      image_size
   lowercase__  :   Tuple    		=      patch_size
   lowercase__  :   Tuple    		=      num_channels
   lowercase__  :   Dict    		=      qkv_bias
   lowercase__  :   List[Any]    		=      backbone_out_indices
   if readout_type not in ["ignore", "add", "project"]:
     raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""")
   lowercase__  :   Dict    		=      readout_type
   lowercase__  :   Tuple    		=      reassemble_factors
   lowercase__  :   Any    		=      neck_hidden_sizes
   lowercase__  :   Dict    		=      fusion_hidden_size
   lowercase__  :   Tuple    		=      head_in_index
   lowercase__  :   Tuple    		=      use_batch_norm_in_fusion_residual
   # auxiliary head attributes (semantic segmentation)
   lowercase__  :   Tuple    		=      use_auxiliary_head
   lowercase__  :   int    		=      auxiliary_loss_weight
   lowercase__  :   Union[str, Any]    		=      semantic_loss_ignore_index
   lowercase__  :   str    		=      semantic_classifier_dropout



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      copy.deepcopy(self.__dict__)

   if output["backbone_config"] is not None:
     lowercase__  :   Optional[Any]    		=      self.backbone_config.to_dict()

   lowercase__  :   Dict    		=      self.__class__.model_type
   return output






