






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

       '''simple docstring'''



       def __init__(							self			,						a__    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						data



       def __iter__(							self    ) ->      List[str]:






            '''simple docstring'''





            for element in self.data:
                 yield element






def   UpperCamelCase  (       snake_case__     :   Optional[Any]=True  ):




     '''simple docstring'''






     __snake_case			:Union[str, Any]          =						Accelerator(even_batches=snake_case__  )
     assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
     return accelerator






def   UpperCamelCase  (       snake_case__     :   Accelerator	,snake_case__     :   int	,snake_case__     :   int	,snake_case__     :   bool = False  ):




     '''simple docstring'''






     if iterable:
          __snake_case			:List[str]          =						DummyIterableDataset(torch.as_tensor(range(snake_case__  )  )  )
     else:
          __snake_case			:Optional[int]          =						TensorDataset(torch.as_tensor(range(snake_case__  )  )  )

     __snake_case			:List[str]          =						DataLoader(snake_case__	,batch_size=snake_case__  )
     __snake_case			:List[Any]          =						accelerator.prepare(snake_case__  )

     return dl






def   UpperCamelCase  (       snake_case__     :   Accelerator	,snake_case__     :   int	,snake_case__     :   int	,snake_case__     :   List[int]	,snake_case__     :   List[int]	,):




     '''simple docstring'''






     __snake_case			:Any          =						create_dataloader(accelerator=snake_case__	,dataset_size=snake_case__	,batch_size=snake_case__  )

     __snake_case			:List[Any]          =						[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  (       ):




     '''simple docstring'''






     __snake_case			:List[str]          =						create_accelerator()

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






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			:Optional[Any]          =						create_accelerator(even_batches=snake_case__  )

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






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			:Dict          =						create_accelerator(even_batches=snake_case__  )

     __snake_case			:Dict          =						torch.nn.Linear(1	,1  )
     __snake_case			:Optional[Any]          =						accelerator.prepare(snake_case__  )

     __snake_case			:Optional[int]          =						create_dataloader(snake_case__	,dataset_size=3	,batch_size=1  )

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




     '''simple docstring'''






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

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






def   UpperCamelCase  (       ):




     '''simple docstring'''






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

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




     '''simple docstring'''






     __snake_case			:List[str]          =						True
     __snake_case			:Union[str, Any]          =						False
     __snake_case			:Tuple          =						create_accelerator(even_batches=snake_case__  )
     __snake_case			:Union[str, Any]          =						torch.nn.Linear(1	,1  )
     __snake_case			:Dict          =						accelerator.prepare(snake_case__  )
     create_dataloader(snake_case__	,dataset_size=3	,batch_size=1	,iterable=snake_case__  )
     __snake_case			:List[str]          =						create_dataloader(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=snake_case__  ):
                    __snake_case			:List[str]          =						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  (       ):




     '''simple docstring'''






     __snake_case			:Optional[int]          =						create_accelerator()
     __snake_case			:int          =						torch.nn.Linear(1	,1  )
     __snake_case			:List[str]          =						accelerator.prepare(snake_case__  )
     create_dataloader(snake_case__	,dataset_size=3	,batch_size=1	,iterable=snake_case__  )

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

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






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			: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"""  )
     __snake_case			:Tuple          =						accelerator.state.distributed_type
     __snake_case			:Any          =						DistributedType.FSDP
     test_join_raises_warning_for_non_ddp_distributed(snake_case__  )
     __snake_case			:Optional[Any]          =						original_state


if __name__ == "__main__":
     main()










import numpy as np
import torch
from torch.utils.data import DataLoader

from accelerate.utils.dataclasses import DistributedType




class 			snake_case__   :

       '''simple docstring'''



       def __init__(							self			,						a__=2			,						a__=3			,						a__=64			,						a__=None    ) ->      int:






            '''simple docstring'''





            __snake_case			:Any          =						np.random.default_rng(a__    )
            __snake_case			:List[str]          =						length
            __snake_case			:Optional[Any]          =						rng.normal(size=(length,)    ).astype(np.floataa    )
            __snake_case			:Optional[int]          =						a * self.x + b + rng.normal(scale=0.1			,						size=(length,)    ).astype(np.floataa    )



       def __len__(							self    ) ->      str:






            '''simple docstring'''





            return self.length



       def __getitem__(							self			,						a__    ) ->      int:






            '''simple docstring'''





            return {"x": self.x[i], "y": self.y[i]}




class 			snake_case__   (							torch.nn.Module):

       '''simple docstring'''



       def __init__(							self			,						a__=0			,						a__=0			,						a__=False    ) ->      List[str]:






            '''simple docstring'''





            super().__init__()
            __snake_case			:Any          =						torch.nn.Parameter(torch.tensor([2, 3]    ).float()    )
            __snake_case			:int          =						torch.nn.Parameter(torch.tensor([2, 3]    ).float()    )
            __snake_case			:Dict          =						True



       def 					__lowercase						(							self			,						a__=None    ) ->      Optional[Any]:






            '''simple docstring'''





            if self.first_batch:
                 print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}'''    )
                 __snake_case			:Tuple          =						False
            return x * self.a[0] + self.b[0]




class 			snake_case__   (							torch.nn.Module):

       '''simple docstring'''



       def __init__(							self			,						a__=0			,						a__=0			,						a__=False    ) ->      List[str]:






            '''simple docstring'''





            super().__init__()
            __snake_case			:Optional[int]          =						torch.nn.Parameter(torch.tensor(a__    ).float()    )
            __snake_case			:List[str]          =						torch.nn.Parameter(torch.tensor(a__    ).float()    )
            __snake_case			:str          =						True



       def 					__lowercase						(							self			,						a__=None    ) ->      str:






            '''simple docstring'''





            if self.first_batch:
                 print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}'''    )
                 __snake_case			:List[Any]          =						False
            return x * self.a + self.b






def   UpperCamelCase  (       snake_case__     :   Optional[int]	,snake_case__     :   int = 16  ):




     '''simple docstring'''






     from datasets import load_dataset
     from transformers import AutoTokenizer

     __snake_case			:Union[str, Any]          =						AutoTokenizer.from_pretrained("""bert-base-cased"""  )
     __snake_case			:Dict          =						{"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""}
     __snake_case			:Any          =						load_dataset("""csv"""	,data_files=snake_case__  )
     __snake_case			:Dict          =						datasets["""train"""].unique("""label"""  )

     __snake_case			:List[Any]          =						{v: i for i, v in enumerate(snake_case__  )}

     def tokenize_function(snake_case__     :   List[Any]  ):
          # max_length=None => use the model max length (it's actually the default)
          __snake_case			:Optional[Any]          =						tokenizer(
              examples["""sentence1"""]	,examples["""sentence2"""]	,truncation=snake_case__	,max_length=snake_case__	,padding="""max_length"""  )
          if "label" in examples:
               __snake_case			:Dict          =						[label_to_id[l] for l in examples["""label"""]]
          return outputs

     # Apply the method we just defined to all the examples in all the splits of the dataset
     __snake_case			:List[str]          =						datasets.map(
         snake_case__	,batched=snake_case__	,remove_columns=["""sentence1""", """sentence2""", """label"""]	,)

     def collate_fn(snake_case__     :   Optional[int]  ):
          # On TPU it's best to pad everything to the same length or training will be very slow.
          if accelerator.distributed_type == DistributedType.TPU:
               return tokenizer.pad(snake_case__	,padding="""max_length"""	,max_length=128	,return_tensors="""pt"""  )
          return tokenizer.pad(snake_case__	,padding="""longest"""	,return_tensors="""pt"""  )

     # Instantiate dataloaders.
     __snake_case			:List[Any]          =						DataLoader(tokenized_datasets["""train"""]	,shuffle=snake_case__	,collate_fn=snake_case__	,batch_size=2  )
     __snake_case			:str          =						DataLoader(tokenized_datasets["""validation"""]	,shuffle=snake_case__	,collate_fn=snake_case__	,batch_size=1  )

     return train_dataloader, eval_dataloader


