






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


				def __init__(					self ,						_lowerCAmelCase      ):
											_lowercase							:   Optional[Any] 							=   data


				def __iter__(					self      ):
											for element in self.data:
																		yield element






def    __magic_name__    (	SCREAMING_SNAKE_CASE=True				)     ->    List[Any]:
							_lowercase							:   List[str] 							=   Accelerator(even_batches=SCREAMING_SNAKE_CASE				)
							assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
							return accelerator






def    __magic_name__    (	SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE = False				)     ->    Union[str, Any]:
							if iterable:
														_lowercase							:   Optional[int] 							=   DummyIterableDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE				)				)				)
							else:
														_lowercase							:   Union[str, Any] 							=   TensorDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE				)				)				)

							_lowercase							:   Any 							=   DataLoader(SCREAMING_SNAKE_CASE     ,     batch_size=SCREAMING_SNAKE_CASE				)
							_lowercase							:   Union[str, Any] 							=   accelerator.prepare(SCREAMING_SNAKE_CASE				)

							return dl






def    __magic_name__    (	SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     )     ->    Optional[int]:
							_lowercase							:   Union[str, Any] 							=   create_dataloader(accelerator=SCREAMING_SNAKE_CASE     ,     dataset_size=SCREAMING_SNAKE_CASE     ,     batch_size=SCREAMING_SNAKE_CASE				)

							_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    __magic_name__    (	)     ->    Any:
							_lowercase							:   Dict 							=   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    __magic_name__    (	)     ->    List[str]:
							_lowercase							:   Dict 							=   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    __magic_name__    (	)     ->    int:
							_lowercase							:   Optional[Any] 							=   create_accelerator(even_batches=SCREAMING_SNAKE_CASE				)

							_lowercase							:   Union[str, Any] 							=   torch.nn.Linear(1     ,     1				)
							_lowercase							:   Optional[Any] 							=   accelerator.prepare(SCREAMING_SNAKE_CASE				)

							_lowercase							:   Union[str, Any] 							=   create_dataloader(SCREAMING_SNAKE_CASE     ,     dataset_size=3     ,     batch_size=1				)

							_lowercase							:   str 							=   []
							with accelerator.join_uneven_inputs([ddp_model]				):
														for batch_idx, batch in enumerate(SCREAMING_SNAKE_CASE				):
																					_lowercase							:   Tuple 							=   ddp_model(batch[0].float()				)
																					_lowercase							:   List[Any] 							=   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    __magic_name__    (	SCREAMING_SNAKE_CASE				)     ->    Optional[Any]:
							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    __magic_name__    (	)     ->    Optional[int]:
							_lowercase							:   Union[str, Any] 							=   True
							_lowercase							:   Any 							=   False
							_lowercase							:   Tuple 							=   create_accelerator(even_batches=SCREAMING_SNAKE_CASE				)
							_lowercase							:   List[str] 							=   torch.nn.Linear(1     ,     1				)
							_lowercase							:   Optional[int] 							=   accelerator.prepare(SCREAMING_SNAKE_CASE				)
							_lowercase							:   Any 							=   create_dataloader(SCREAMING_SNAKE_CASE     ,     dataset_size=3     ,     batch_size=1				)
							_lowercase							:   str 							=   create_dataloader(SCREAMING_SNAKE_CASE     ,     dataset_size=3     ,     batch_size=1				)

							with accelerator.join_uneven_inputs([ddp_model]     ,     even_batches=SCREAMING_SNAKE_CASE				):
														_lowercase							:   str 							=   train_dl.batch_sampler.even_batches
														_lowercase							:   Tuple 							=   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    __magic_name__    (	)     ->    Tuple:
							_lowercase							:   Any 							=   True
							_lowercase							:   Union[str, Any] 							=   False
							_lowercase							:   Tuple 							=   create_accelerator(even_batches=SCREAMING_SNAKE_CASE				)
							_lowercase							:   Union[str, Any] 							=   torch.nn.Linear(1     ,     1				)
							_lowercase							:   str 							=   accelerator.prepare(SCREAMING_SNAKE_CASE				)
							create_dataloader(SCREAMING_SNAKE_CASE     ,     dataset_size=3     ,     batch_size=1     ,     iterable=SCREAMING_SNAKE_CASE				)
							_lowercase							:   Dict 							=   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				):
																												_lowercase							:   Dict 							=   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    __magic_name__    (	)     ->    Tuple:
							_lowercase							:   Optional[Any] 							=   create_accelerator()
							_lowercase							:   str 							=   torch.nn.Linear(1     ,     1				)
							_lowercase							:   List[str] 							=   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    __magic_name__    (	)     ->    List[str]:
							_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							:   Tuple 							=   accelerator.state.distributed_type
							_lowercase							:   List[str] 							=   DistributedType.FSDP
							test_join_raises_warning_for_non_ddp_distributed(SCREAMING_SNAKE_CASE				)
							_lowercase							:   List[str] 							=   original_state


if __name__ == "__main__":
							main()











'''simple docstring'''

from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


a   	=    logging.get_logger(__name__)

a   	=    {
    "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
    "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
    "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
    "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
    "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
    "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
}







class __a			( _snake_case      ):
   __UpperCamelCase :			List[str]						   =						'bloom'
   __UpperCamelCase :			Optional[Any]						   =						['past_key_values']
   __UpperCamelCase :			Optional[int]						   =						{
       'num_hidden_layers': 'n_layer',
       'num_attention_heads': 'n_head',
   }





   def __init__(       self					:      Union[str, Any]					,lowerCamelCase					:      str=25_0880					,lowerCamelCase					:      List[Any]=64					,lowerCamelCase					:      Optional[Any]=2					,lowerCamelCase					:      Tuple=8					,lowerCamelCase					:      Union[str, Any]=1E-5					,lowerCamelCase					:      Optional[Any]=0.02					,lowerCamelCase					:      str=True					,lowerCamelCase					:      List[Any]=1					,lowerCamelCase					:      Union[str, Any]=2					,lowerCamelCase					:      Optional[int]=False					,lowerCamelCase					:      Optional[int]=0.0					,lowerCamelCase					:      List[Any]=0.0					,lowerCamelCase					:      Optional[Any]=1					,lowerCamelCase					:      Tuple=False					,**lowerCamelCase					:      str					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							vocab_size
      # Backward compatibility with n_embed kwarg
      __SCREAMING_SNAKE_CASE   				=							kwargs.pop("""n_embed"""					,lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							hidden_size if n_embed is None else n_embed
      __SCREAMING_SNAKE_CASE   				=							n_layer
      __SCREAMING_SNAKE_CASE   				=							n_head
      __SCREAMING_SNAKE_CASE   				=							layer_norm_epsilon
      __SCREAMING_SNAKE_CASE   				=							initializer_range
      __SCREAMING_SNAKE_CASE   				=							use_cache
      __SCREAMING_SNAKE_CASE   				=							pretraining_tp
      __SCREAMING_SNAKE_CASE   				=							apply_residual_connection_post_layernorm
      __SCREAMING_SNAKE_CASE   				=							hidden_dropout
      __SCREAMING_SNAKE_CASE   				=							attention_dropout

      __SCREAMING_SNAKE_CASE   				=							bos_token_id
      __SCREAMING_SNAKE_CASE   				=							eos_token_id
      __SCREAMING_SNAKE_CASE   				=							slow_but_exact

      super().__init__(bos_token_id=lowerCamelCase					,eos_token_id=lowerCamelCase					,**lowerCamelCase     )







class __a			( _snake_case      ):
   __UpperCamelCase :			int						   =						version.parse('1.12'      )





   def __init__(       self					:      Optional[int]					,lowerCamelCase					:      PretrainedConfig					,lowerCamelCase					:      str = "default"					,lowerCamelCase					:      List[PatchingSpec] = None					,lowerCamelCase					:      bool = False					,):

      '''simple docstring'''

      super().__init__(lowerCamelCase					,task=lowerCamelCase					,patching_specs=lowerCamelCase					,use_past=lowerCamelCase     )
      if not getattr(self._config					,"""pad_token_id"""					,lowerCamelCase     ):
         # TODO: how to do that better?
         __SCREAMING_SNAKE_CASE   				=							0





   @property
   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}     )
      if self.use_past:
         # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
         self.fill_with_past_key_values_(lowerCamelCase					,direction="""inputs"""					,inverted_values_shape=lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """past_sequence + sequence"""}
      else:
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """sequence"""}

      return common_inputs





   @property
   def   UpperCAmelCase__  (       self					:      Tuple     ):

      '''simple docstring'''

      return self._config.n_layer





   @property
   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      return self._config.n_head





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 1E-3





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      "PreTrainedTokenizer"					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      bool = False					,lowerCamelCase					:      Optional["TensorType"] = None					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							super(lowerCamelCase					,self     ).generate_dummy_inputs(
          lowerCamelCase					,batch_size=lowerCamelCase					,seq_length=lowerCamelCase					,is_pair=lowerCamelCase					,framework=lowerCamelCase     )

      # We need to order the input in the way they appears in the forward()
      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}     )

      # Need to add the past_keys
      if self.use_past:
         if not is_torch_available():
            raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""     )
         else:
            import torch

            __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							common_inputs["""input_ids"""].shape
            # Not using the same length for past_key_values
            __SCREAMING_SNAKE_CASE   				=							seqlen + 2
            __SCREAMING_SNAKE_CASE   				=							self._config.hidden_size // self.num_attention_heads
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                head_dim,
                past_key_values_length,
            )
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                past_key_values_length,
                head_dim,
            )
            __SCREAMING_SNAKE_CASE   				=							[
                (torch.zeros(lowerCamelCase     ), torch.zeros(lowerCamelCase     )) for _ in range(self.num_layers     )
            ]

      __SCREAMING_SNAKE_CASE   				=							common_inputs["""attention_mask"""]
      if self.use_past:
         __SCREAMING_SNAKE_CASE   				=							ordered_inputs["""attention_mask"""].dtype
         __SCREAMING_SNAKE_CASE   				=							torch.cat(
             [ordered_inputs["""attention_mask"""], torch.ones(lowerCamelCase					,lowerCamelCase					,dtype=lowerCamelCase     )]					,dim=1     )

      return ordered_inputs





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 13





