





'''simple docstring'''





from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    get_torch_dist_unique_port,
    require_torch_multi_gpu,
    require_torch_neuroncore,
)
from transformers.training_args import ParallelMode
from transformers.utils import logging


__A             =       logging.get_logger(__name__)


if is_torch_available():
     import torch
     from torch import nn
     from torch.utils.data import Dataset

     from transformers import Trainer



     class      _SCREAMING_SNAKE_CASE		(			_lowercase					):







      '''simple docstring'''

      def __init__(self       :     str ,				UpperCAmelCase_       :     int = 101) ->Tuple:



        '''simple docstring'''



        lowerCamelCase__:   Optional[int]    						=length

      def __len__(self       :     int) ->Any:



        '''simple docstring'''



        return self.length







      def __getitem__(self       :     Optional[int] ,				UpperCAmelCase_       :     List[Any]) ->int:



        '''simple docstring'''



        return i



     class      _SCREAMING_SNAKE_CASE		:







      '''simple docstring'''

      def __call__(self       :     str ,				UpperCAmelCase_       :     List[Any]) ->Any:



        '''simple docstring'''



        return {"input_ids": torch.tensor(A_), "labels": torch.tensor(A_)}



     class      _SCREAMING_SNAKE_CASE		(			nn.Module					):







      '''simple docstring'''

      def __init__(self       :     Optional[Any]) ->Any:



        '''simple docstring'''



        super().__init__()
        # Add some (unused) params otherwise DDP will complain.
        lowerCamelCase__:   Optional[int]    						=nn.Linear(120 ,				80)







      def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple ,				UpperCAmelCase_       :     Tuple ,				UpperCAmelCase_       :     Tuple=None) ->Optional[Any]:



        '''simple docstring'''



        if labels is not None:
          return torch.tensor(0.0 ,				device=input_ids.device), input_ids
        else:
          return input_ids



class      _SCREAMING_SNAKE_CASE		(			_lowercase					):







 '''simple docstring'''

 @require_torch_neuroncore
 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Tuple    						=F"""--nproc_per_node=2\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        """.split()
   lowerCamelCase__:   List[str]    						=self.get_auto_remove_tmp_dir()
   lowerCamelCase__:   List[Any]    						=F"""--output_dir {output_dir}""".split()
   lowerCamelCase__:   Optional[Any]    						=["torchrun"] + distributed_args + args
   execute_subprocess_async(A_ ,				env=self.get_env())
   # successful return here == success - any errors would have caused an error in the sub-call



class      _SCREAMING_SNAKE_CASE		(			_lowercase					):







 '''simple docstring'''

 @require_torch_multi_gpu
 def 							SCREAMING_SNAKE_CASE_      (self       :     Any) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=F"""--nproc_per_node={torch.cuda.device_count()}\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        """.split()
   lowerCamelCase__:   str    						=self.get_auto_remove_tmp_dir()
   lowerCamelCase__:   Optional[int]    						=F"""--output_dir {output_dir}""".split()
   lowerCamelCase__:   Any    						=["torchrun"] + distributed_args + args
   execute_subprocess_async(A_ ,				env=self.get_env())
   # successful return here == success - any errors would have caused an error in the sub-call


if __name__ == "__main__":
     # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs:
     #
     # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py

     __A             =       HfArgumentParser((TrainingArguments,))
     __A             =       parser.parse_args_into_dataclasses()[0]

     logger.warning(
         f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, '
         f'distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}'
     )

     # Essentially, what we want to verify in the distributed case is that we get all samples back,
     # in the right order. (this is crucial for prediction for instance)
     for dataset_length in [101, 40, 7]:
          __A             =       DummyDataset(dataset_length)





          def   lowerCAmelCase_				( __a	)  ->	Optional[Any]:







            """simple docstring"""





            lowerCamelCase__:   Optional[Any]    						=list(range(len(snake_case__	)	)	)
            lowerCamelCase__:   List[str]    						=p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
            if not success and training_args.local_rank == 0:
              logger.warning(
                  "Predictions and/or labels do not match expected results:\n  - predictions: "
                  F"""{p.predictions.tolist()}\n  - labels: {p.label_ids.tolist()}\n  - expected: {sequential}"""	)
            return {"success": success}

          __A             =       Trainer(
              model=DummyModel(),
              args=training_args,
              data_collator=DummyDataCollator(),
              eval_dataset=dataset,
              compute_metrics=compute_metrics,
          )
          __A             =       trainer.evaluate()
          logger.info(metrics)
          if metrics["eval_success"] is not True:
               logger.error(metrics)
               exit(1)

          __A             =       trainer.predict(dataset)
          logger.info(p.metrics)
          if p.metrics["test_success"] is not True:
               logger.error(p.metrics)
               exit(1)

          __A             =       2

          __A             =       trainer.evaluate()
          logger.info(metrics)
          if metrics["eval_success"] is not True:
               logger.error(metrics)
               exit(1)

          __A             =       trainer.predict(dataset)
          logger.info(p.metrics)
          if p.metrics["test_success"] is not True:
               logger.error(p.metrics)
               exit(1)






          __A             =       None








from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A             =       logging.get_logger(__name__)

__A             =       {
    "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
    "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
}



class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''
 lowercase_	=    "falcon"
 lowercase_	=    ["past_key_values"]

 def __init__(self       :     str ,				UpperCAmelCase_       :     Optional[Any]=65_024 ,				UpperCAmelCase_       :     Union[str, Any]=4_544 ,				UpperCAmelCase_       :     Any=32 ,				UpperCAmelCase_       :     str=71 ,				UpperCAmelCase_       :     int=1E-5 ,				UpperCAmelCase_       :     int=0.02 ,				UpperCAmelCase_       :     int=True ,				UpperCAmelCase_       :     Tuple=0.0 ,				UpperCAmelCase_       :     str=0.0 ,				UpperCAmelCase_       :     List[Any]=None ,				UpperCAmelCase_       :     Any=False ,				UpperCAmelCase_       :     Tuple=False ,				UpperCAmelCase_       :     List[Any]=True ,				UpperCAmelCase_       :     Dict=True ,				UpperCAmelCase_       :     List[str]=False ,				UpperCAmelCase_       :     str=11 ,				UpperCAmelCase_       :     List[Any]=11 ,				**UpperCAmelCase_       :     str ,				) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=vocab_size
   # Backward compatibility with n_embed kwarg
   lowerCamelCase__:   List[Any]    						=kwargs.pop("n_embed" ,				UpperCAmelCase_)
   lowerCamelCase__:   Dict    						=hidden_size if n_embed is None else n_embed
   lowerCamelCase__:   Tuple    						=num_hidden_layers
   lowerCamelCase__:   Dict    						=num_attention_heads
   lowerCamelCase__:   Optional[Any]    						=layer_norm_epsilon
   lowerCamelCase__:   Union[str, Any]    						=initializer_range
   lowerCamelCase__:   Union[str, Any]    						=use_cache
   lowerCamelCase__:   str    						=hidden_dropout
   lowerCamelCase__:   Tuple    						=attention_dropout

   lowerCamelCase__:   Dict    						=bos_token_id
   lowerCamelCase__:   Union[str, Any]    						=eos_token_id
   lowerCamelCase__:   Any    						=num_attention_heads if num_kv_heads is None else num_kv_heads
   lowerCamelCase__:   Dict    						=alibi
   lowerCamelCase__:   Optional[Any]    						=new_decoder_architecture
   lowerCamelCase__:   List[str]    						=multi_query  # Ignored when new_decoder_architecture is True
   lowerCamelCase__:   Tuple    						=parallel_attn
   lowerCamelCase__:   Optional[Any]    						=bias

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

 @property
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Dict:



   '''simple docstring'''



   return self.hidden_size // self.num_attention_heads







 @property
 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->List[Any]:



   '''simple docstring'''



   return not self.alibi

