






'''simple docstring'''



import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          DistilBertForMaskedLM,
          DistilBertForMultipleChoice,
          DistilBertForQuestionAnswering,
          DistilBertForSequenceClassification,
          DistilBertForTokenClassification,
          DistilBertModel,
      )
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      def __init__(			self      :		List[str]  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		Tuple=13  ,   UpperCAmelCase      :		Dict=7  ,   UpperCAmelCase      :		int=True  ,   UpperCAmelCase      :		Union[str, Any]=True  ,   UpperCAmelCase      :		Dict=False  ,   UpperCAmelCase      :		List[Any]=True  ,   UpperCAmelCase      :		Dict=99  ,   UpperCAmelCase      :		Union[str, Any]=32  ,   UpperCAmelCase      :		Dict=5  ,   UpperCAmelCase      :		Tuple=4  ,   UpperCAmelCase      :		List[str]=37  ,   UpperCAmelCase      :		Tuple="gelu"  ,   UpperCAmelCase      :		List[str]=0.1  ,   UpperCAmelCase      :		Tuple=0.1  ,   UpperCAmelCase      :		int=512  ,   UpperCAmelCase      :		Optional[Any]=16  ,   UpperCAmelCase      :		Tuple=2  ,   UpperCAmelCase      :		Optional[int]=0.0_2  ,   UpperCAmelCase      :		Optional[int]=3  ,   UpperCAmelCase      :		Optional[int]=4  ,   UpperCAmelCase      :		List[Any]=None  ,   )	->	List[Any]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=parent
       lowercase       : Tuple						=batch_size
       lowercase       : Dict						=seq_length
       lowercase       : List[Any]						=is_training
       lowercase       : int						=use_input_mask
       lowercase       : List[Any]						=use_token_type_ids
       lowercase       : List[Any]						=use_labels
       lowercase       : Any						=vocab_size
       lowercase       : List[Any]						=hidden_size
       lowercase       : str						=num_hidden_layers
       lowercase       : Dict						=num_attention_heads
       lowercase       : Union[str, Any]						=intermediate_size
       lowercase       : Union[str, Any]						=hidden_act
       lowercase       : List[Any]						=hidden_dropout_prob
       lowercase       : str						=attention_probs_dropout_prob
       lowercase       : Optional[Any]						=max_position_embeddings
       lowercase       : Dict						=type_vocab_size
       lowercase       : List[Any]						=type_sequence_label_size
       lowercase       : List[str]						=initializer_range
       lowercase       : Union[str, Any]						=num_labels
       lowercase       : List[str]						=num_choices
       lowercase       : Union[str, Any]						=scope






      def 					A__   (			self      :		Any		)	->	Dict:


       '''simple docstring'''

       lowercase       : Tuple						=ids_tensor([self.batch_size, self.seq_length]  ,   self.vocab_size		)

       lowercase       : Dict						=None
       if self.use_input_mask:
        lowercase       : Optional[Any]						=random_attention_mask([self.batch_size, self.seq_length]		)

       lowercase       : Union[str, Any]						=None
       lowercase       : int						=None
       lowercase       : int						=None
       if self.use_labels:
        lowercase       : Dict						=ids_tensor([self.batch_size]  ,   self.type_sequence_label_size		)
        lowercase       : Any						=ids_tensor([self.batch_size, self.seq_length]  ,   self.num_labels		)
        lowercase       : Union[str, Any]						=ids_tensor([self.batch_size]  ,   self.num_choices		)

       lowercase       : Tuple						=self.get_config()

       return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






      def 					A__   (			self      :		Any		)	->	Tuple:


       '''simple docstring'''

       return DistilBertConfig(
           vocab_size=self.vocab_size  ,   dim=self.hidden_size  ,   n_layers=self.num_hidden_layers  ,   n_heads=self.num_attention_heads  ,   hidden_dim=self.intermediate_size  ,   hidden_act=self.hidden_act  ,   dropout=self.hidden_dropout_prob  ,   attention_dropout=self.attention_probs_dropout_prob  ,   max_position_embeddings=self.max_position_embeddings  ,   initializer_range=self.initializer_range  ,   )






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		int  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		Dict		)	->	List[Any]:


       '''simple docstring'''

       lowercase       : int						=DistilBertModel(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : List[str]						=model(UpperCAmelCase  ,   UpperCAmelCase		)
       lowercase       : Dict						=model(UpperCAmelCase		)
       self.parent.assertEqual(result.last_hidden_state.shape  ,   (self.batch_size, self.seq_length, self.hidden_size)		)






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Optional[int]		)	->	int:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=DistilBertForMaskedLM(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Optional[Any]						=model(UpperCAmelCase  ,   attention_mask=UpperCAmelCase  ,   labels=UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.seq_length, self.vocab_size)		)






      def 					A__   (			self      :		Union[str, Any]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		int  ,   UpperCAmelCase      :		List[str]		)	->	List[str]:


       '''simple docstring'''

       lowercase       : List[Any]						=DistilBertForQuestionAnswering(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Any						=model(
           UpperCAmelCase  ,   attention_mask=UpperCAmelCase  ,   start_positions=UpperCAmelCase  ,   end_positions=UpperCAmelCase		)
       self.parent.assertEqual(result.start_logits.shape  ,   (self.batch_size, self.seq_length)		)
       self.parent.assertEqual(result.end_logits.shape  ,   (self.batch_size, self.seq_length)		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Dict		)	->	str:


       '''simple docstring'''

       lowercase       : Tuple						=self.num_labels
       lowercase       : int						=DistilBertForSequenceClassification(UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Any						=model(UpperCAmelCase  ,   attention_mask=UpperCAmelCase  ,   labels=UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_labels)		)






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Union[str, Any]		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase       : Tuple						=self.num_labels
       lowercase       : List[str]						=DistilBertForTokenClassification(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()

       lowercase       : Optional[int]						=model(UpperCAmelCase  ,   attention_mask=UpperCAmelCase  ,   labels=UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.seq_length, self.num_labels)		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		int  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		Optional[Any]		)	->	List[Any]:


       '''simple docstring'''

       lowercase       : Tuple						=self.num_choices
       lowercase       : Any						=DistilBertForMultipleChoice(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Union[str, Any]						=input_ids.unsqueeze(1		).expand(-1  ,   self.num_choices  ,   -1		).contiguous()
       lowercase       : str						=input_mask.unsqueeze(1		).expand(-1  ,   self.num_choices  ,   -1		).contiguous()
       lowercase       : str						=model(
           UpperCAmelCase  ,   attention_mask=UpperCAmelCase  ,   labels=UpperCAmelCase  ,   )
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_choices)		)






      def 					A__   (			self      :		Optional[int]		)	->	str:


       '''simple docstring'''

       lowercase       : List[str]						=self.prepare_config_and_inputs()
       ((lowercase)	,		(lowercase)	,		(lowercase)	,		(lowercase)	,		(lowercase)	,		(lowercase))       : List[str]						=config_and_inputs
       lowercase       : Union[str, Any]						={'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict





@require_torch
class UpperCAmelCase_       (     __A					,							__A					,							unittest.TestCase					):




      """simple docstring"""




      UpperCamelCase_             =      (
          (
              DistilBertModel,
              DistilBertForMaskedLM,
              DistilBertForMultipleChoice,
              DistilBertForQuestionAnswering,
              DistilBertForSequenceClassification,
              DistilBertForTokenClassification,
          )
          if is_torch_available()
          else None
      )
      UpperCamelCase_             =      (
          {
              '''feature-extraction''': DistilBertModel,
              '''fill-mask''': DistilBertForMaskedLM,
              '''question-answering''': DistilBertForQuestionAnswering,
              '''text-classification''': DistilBertForSequenceClassification,
              '''token-classification''': DistilBertForTokenClassification,
              '''zero-shot''': DistilBertForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      UpperCamelCase_             =      True
      UpperCamelCase_             =      True
      UpperCamelCase_             =      True
      UpperCamelCase_             =      True






      def 					A__   (			self      :		Any		)	->	int:


       '''simple docstring'''

       lowercase       : List[Any]						=DistilBertModelTester(self		)
       lowercase       : Union[str, Any]						=ConfigTester(self  ,   config_class=UpperCAmelCase  ,   dim=37		)






      def 					A__   (			self      :		Tuple		)	->	str:


       '''simple docstring'''

       self.config_tester.run_common_tests()






      def 					A__   (			self      :		Optional[int]		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Any						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase		)






      def 					A__   (			self      :		Tuple		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Optional[int]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase		)






      def 					A__   (			self      :		Tuple		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Any						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase		)






      def 					A__   (			self      :		int		)	->	str:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase		)






      def 					A__   (			self      :		List[Any]		)	->	str:


       '''simple docstring'''

       lowercase       : Optional[int]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase		)






      def 					A__   (			self      :		Dict		)	->	int:


       '''simple docstring'''

       lowercase       : int						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase		)






      @slow
      def 					A__   (			self      :		List[str]		)	->	str:


       '''simple docstring'''

       for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase       : List[str]						=DistilBertModel.from_pretrained(UpperCAmelCase		)
        self.assertIsNotNone(UpperCAmelCase		)






      @slow
      @require_torch_gpu
      def 					A__   (			self      :		List[Any]		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase	,		lowercase       : Optional[int]						=self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes:
        # BertForMultipleChoice behaves incorrectly in JIT environments.
        if model_class == DistilBertForMultipleChoice:
         return

        lowercase       : Optional[Any]						=True
        lowercase       : Tuple						=model_class(config=UpperCAmelCase		)

        lowercase       : Tuple						=self._prepare_for_class(UpperCAmelCase  ,   UpperCAmelCase		)
        lowercase       : Tuple						=torch.jit.trace(
            UpperCAmelCase  ,   (inputs_dict['''input_ids'''].to('''cpu'''		), inputs_dict['''attention_mask'''].to('''cpu'''		))		)

        with tempfile.TemporaryDirectory() as tmp:
         torch.jit.save(UpperCAmelCase  ,   os.path.join(UpperCAmelCase  ,   '''traced_model.pt'''		)		)
         lowercase       : Any						=torch.jit.load(os.path.join(UpperCAmelCase  ,   '''traced_model.pt'''		)  ,   map_location=UpperCAmelCase		)
         loaded(inputs_dict['''input_ids'''].to(UpperCAmelCase		)  ,   inputs_dict['''attention_mask'''].to(UpperCAmelCase		)		)





@require_torch
class UpperCAmelCase_       (     unittest.TestCase					):




      """simple docstring"""




      @slow
      def 					A__   (			self      :		str		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Dict						=DistilBertModel.from_pretrained('''distilbert-base-uncased'''		)
       lowercase       : List[str]						=torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]		)
       lowercase       : List[Any]						=torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]		)
       with torch.no_grad():
        lowercase       : Any						=model(UpperCAmelCase  ,   attention_mask=UpperCAmelCase		)[0]
       lowercase       : Union[str, Any]						=torch.Size((1, 11, 768)		)
       self.assertEqual(output.shape  ,   UpperCAmelCase		)
       lowercase       : Union[str, Any]						=torch.tensor(
           [[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]]		)

       self.assertTrue(torch.allclose(output[:, 1:4, 1:4]  ,   UpperCAmelCase  ,   atol=1e-4		)		)











'''simple docstring'''



import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand


def 				lowercase_					(     __A			:							List[Any]      )							->   Union[str, Any]:



 """simple docstring"""




 return EnvironmentCommand()


def 				lowercase_					(     __A			:							int      )							->   Dict:



 """simple docstring"""




 return EnvironmentCommand(args.accelerate_config_file      )





class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      @staticmethod
      def 					A__   (			UpperCAmelCase      :		ArgumentParser		)	->	List[str]:


       '''simple docstring'''

       lowercase       : Optional[int]						=parser.add_parser('''env'''		)
       download_parser.set_defaults(func=UpperCAmelCase		)
       download_parser.add_argument(
           '''--accelerate-config_file'''  ,   default=UpperCAmelCase  ,   help='''The accelerate config file to use for the default values in the launching script.'''  ,   )
       download_parser.set_defaults(func=UpperCAmelCase		)






      def __init__(			self      :		Dict  ,   UpperCAmelCase      :		Tuple  ,   *UpperCAmelCase      :		Tuple		)	->	None:


       '''simple docstring'''

       lowercase       : List[str]						=accelerate_config_file






      def 					A__   (			self      :		Tuple		)	->	int:


       '''simple docstring'''

       lowercase       : Optional[Any]						='''not installed'''
       if is_safetensors_available():
        import safetensors

        lowercase       : List[Any]						=safetensors.__version__
       elif importlib.util.find_spec('''safetensors'''		) is not None:
        import safetensors

        lowercase       : List[str]						=f'{safetensors.__version__} but is ignored because of PyTorch version too old.'

       lowercase       : List[str]						='''not installed'''
       lowercase       : str						='''not found'''
       if is_accelerate_available():
        import accelerate
        from accelerate.commands.config import default_config_file, load_config_from_file

        lowercase       : List[str]						=accelerate.__version__
        # Get the default from the config file.
        if self._accelerate_config_file is not None or os.path.isfile(UpperCAmelCase		):
         lowercase       : Dict						=load_config_from_file(self._accelerate_config_file		).to_dict()

        lowercase       : Optional[int]						=(
            '''\n'''.join([f'\t- {prop}: {val}' for prop, val in accelerate_config.items()]		)
            if isinstance(UpperCAmelCase  ,   UpperCAmelCase		)
            else f'\t{accelerate_config}'
        )

       lowercase       : Optional[int]						='''not installed'''
       lowercase       : Optional[Any]						='''NA'''
       if is_torch_available():
        import torch

        lowercase       : List[Any]						=torch.__version__
        lowercase       : Dict						=torch.cuda.is_available()

       lowercase       : Optional[Any]						='''not installed'''
       lowercase       : List[str]						='''NA'''
       if is_tf_available():
        import tensorflow as tf

        lowercase       : List[Any]						=tf.__version__
        try:
         # deprecated in v2.1
         lowercase       : Optional[Any]						=tf.test.is_gpu_available()
        except AttributeError:
         # returns list of devices, convert to bool
         lowercase       : Optional[int]						=bool(tf.config.list_physical_devices('''GPU'''		)		)

       lowercase       : Optional[Any]						='''not installed'''
       lowercase       : Optional[Any]						='''not installed'''
       lowercase       : Optional[Any]						='''not installed'''
       lowercase       : List[str]						='''NA'''
       if is_flax_available():
        import flax
        import jax
        import jaxlib

        lowercase       : Dict						=flax.__version__
        lowercase       : List[Any]						=jax.__version__
        lowercase       : Any						=jaxlib.__version__
        lowercase       : Tuple						=jax.lib.xla_bridge.get_backend().platform

       lowercase       : str						={
           '''`transformers` version''': version,
           '''Platform''': platform.platform(),
           '''Python version''': platform.python_version(),
           '''Huggingface_hub version''': huggingface_hub.__version__,
           '''Safetensors version''': f'{safetensors_version}',
           '''Accelerate version''': f'{accelerate_version}',
           '''Accelerate config''': f'{accelerate_config_str}',
           '''PyTorch version (GPU?)''': f'{pt_version} ({pt_cuda_available})',
           '''Tensorflow version (GPU?)''': f'{tf_version} ({tf_cuda_available})',
           '''Flax version (CPU?/GPU?/TPU?)''': f'{flax_version} ({jax_backend})',
           '''Jax version''': f'{jax_version}',
           '''JaxLib version''': f'{jaxlib_version}',
           '''Using GPU in script?''': '''<fill in>''',
           '''Using distributed or parallel set-up in script?''': '''<fill in>''',
       }

       print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'''		)
       print(self.format_dict(UpperCAmelCase		)		)

       return info






      @staticmethod
      def 					A__   (			UpperCAmelCase      :		Any		)	->	Any:


       '''simple docstring'''

       return "\n".join([f'- {prop}: {val}' for prop, val in d.items()]		) + "\n"



