"""simple docstring"""





import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_UpperCamelCase   :						Any      =    logging.getLogger(__name__)


_UpperCamelCase   :						Optional[Any]      =    list(MODEL_WITH_LM_HEAD_MAPPING.keys())
_UpperCamelCase   :						Any      =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)


@dataclass
class      UpperCAmelCase_	:
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={
              "help": (
                  "The model checkpoint for weights initialization. Leave None if you want to train a model from"
                  " scratch."
              )
          } ,							)
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_a)} ,							)
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "Pretrained config name or path if not the same as model_name"})
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"})
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,							)





@dataclass
class      UpperCAmelCase_	:
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "The input training data file (a text file)."})
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={
              "help": (
                  "The input training data files (multiple files in glob format). "
                  "Very often splitting large files to smaller files can prevent tokenizer going out of memory"
              )
          } ,							)
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} ,							)
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} ,							)
      lowerCamelCase__		:    Optional[str]   =  field(
          default=_a ,							metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} ,							)
      lowerCamelCase__		:    bool   =  field(
          default=_a ,							metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} ,							)

      lowerCamelCase__		:    bool   =  field(
          default=_a ,							metadata={"help": "Train with masked-language modeling loss instead of language modeling."})
      lowerCamelCase__		:    bool   =  field(default=_a ,							metadata={"help": "Whether ot not to use whole word mask."})
      lowerCamelCase__		:    float   =  field(
          default=0.15 ,							metadata={"help": "Ratio of tokens to mask for masked language modeling loss"})
      lowerCamelCase__		:    float   =  field(
          default=1 / 6 ,							metadata={
              "help": (
                  "Ratio of length of a span of masked tokens to surrounding context length for permutation language"
                  " modeling."
              )
          } ,							)
      lowerCamelCase__		:    int   =  field(
          default=5 ,							metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."})

      lowerCamelCase__		:    int   =  field(
          default=-1 ,							metadata={
              "help": (
                  "Optional input sequence length after tokenization."
                  "The training dataset will be truncated in block of this size for training."
                  "Default to the model max input length for single sentence inputs (take into account special tokens)."
              )
          } ,							)
      lowerCamelCase__		:    bool   =  field(
          default=_a ,							metadata={"help": "Overwrite the cached training and evaluation sets"})





def 				a_     (      _lowerCAmelCase  : DataTrainingArguments   , _lowerCAmelCase  : PreTrainedTokenizer   , _lowerCAmelCase  : bool = False   , _lowerCAmelCase  : Optional[str] = None   , ):





       '''simple docstring'''

       def _dataset(_lowerCAmelCase  : Any   , _lowerCAmelCase  : Any=None     ):
              if args.line_by_line:
                     if ref_path is not None:
                            if not args.whole_word_mask or not args.mlm:
                                   raise ValueError('You need to set world whole masking and mlm to True for Chinese Whole Word Mask'     )
                            return LineByLineWithRefDataset(
                                tokenizer=_lowerCAmelCase   , file_path=_lowerCAmelCase   , block_size=args.block_size   , ref_path=_lowerCAmelCase   , )

                     return LineByLineTextDataset(tokenizer=_lowerCAmelCase   , file_path=_lowerCAmelCase   , block_size=args.block_size     )
              else:
                     return TextDataset(
                         tokenizer=_lowerCAmelCase   , file_path=_lowerCAmelCase   , block_size=args.block_size   , overwrite_cache=args.overwrite_cache   , cache_dir=_lowerCAmelCase   , )

       if evaluate:
              return _dataset(args.eval_data_file   , args.eval_ref_file     )
       elif args.train_data_files:
              return ConcatDataset([_dataset(_lowerCAmelCase     ) for f in glob(args.train_data_files     )]     )
       else:
              return _dataset(args.train_data_file   , args.train_ref_file     )





def 				a_     (      ):





       '''simple docstring'''

       lowercase__			:		Any       =	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
       lowercase__    ,      lowercase__    ,      lowercase__			:		List[Any]       =	parser.parse_args_into_dataclasses()

       if data_args.eval_data_file is None and training_args.do_eval:
              raise ValueError(
                  'Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '
                  'or remove the --do_eval argument.'     )
       if (
           os.path.exists(training_args.output_dir     )
           and os.listdir(training_args.output_dir     )
           and training_args.do_train
           and not training_args.overwrite_output_dir
       ):
              raise ValueError(
                  f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
                  ' --overwrite_output_dir to overcome.'     )

       # Setup logging
       logging.basicConfig(
           format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'   , datefmt='%m/%d/%Y %H:%M:%S'   , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN   , )
       logger.warning(
           'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'   , training_args.local_rank   , training_args.device   , training_args.n_gpu   , bool(training_args.local_rank != -1     )   , training_args.fpaa   , )
       # Set the verbosity to info of the Transformers logger (on main process only):
       if is_main_process(training_args.local_rank     ):
              transformers.utils.logging.set_verbosity_info()
              transformers.utils.logging.enable_default_handler()
              transformers.utils.logging.enable_explicit_format()
       logger.info('Training/evaluation parameters %s'   , _lowerCAmelCase     )

       # Set seed
       set_seed(training_args.seed     )

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.

       if model_args.config_name:
              lowercase__			:		List[Any]       =	AutoConfig.from_pretrained(model_args.config_name   , cache_dir=model_args.cache_dir     )
       elif model_args.model_name_or_path:
              lowercase__			:		Any       =	AutoConfig.from_pretrained(model_args.model_name_or_path   , cache_dir=model_args.cache_dir     )
       else:
              lowercase__			:		Union[str, Any]       =	CONFIG_MAPPING[model_args.model_type]()
              logger.warning('You are instantiating a new config instance from scratch.'     )

       if model_args.tokenizer_name:
              lowercase__			:		Dict       =	AutoTokenizer.from_pretrained(model_args.tokenizer_name   , cache_dir=model_args.cache_dir     )
       elif model_args.model_name_or_path:
              lowercase__			:		int       =	AutoTokenizer.from_pretrained(model_args.model_name_or_path   , cache_dir=model_args.cache_dir     )
       else:
              raise ValueError(
                  'You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'
                  ' script, save it,and load it from here, using --tokenizer_name'     )

       if model_args.model_name_or_path:
              lowercase__			:		Optional[Any]       =	AutoModelWithLMHead.from_pretrained(
                  model_args.model_name_or_path   , from_tf=bool('.ckpt' in model_args.model_name_or_path     )   , config=_lowerCAmelCase   , cache_dir=model_args.cache_dir   , )
       else:
              logger.info('Training new model from scratch'     )
              lowercase__			:		int       =	AutoModelWithLMHead.from_config(_lowerCAmelCase     )

       model.resize_token_embeddings(len(_lowerCAmelCase     )     )

       if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
              raise ValueError(
                  'BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'
                  '--mlm flag (masked language modeling).'     )

       if data_args.block_size <= 0:
              lowercase__			:		List[str]       =	tokenizer.max_len
              # Our input block size will be the max possible for the model
       else:
              lowercase__			:		int       =	min(data_args.block_size   , tokenizer.max_len     )

       # Get datasets

       lowercase__			:		Tuple       =	(
           get_dataset(_lowerCAmelCase   , tokenizer=_lowerCAmelCase   , cache_dir=model_args.cache_dir     ) if training_args.do_train else None
       )
       lowercase__			:		Optional[Any]       =	(
           get_dataset(_lowerCAmelCase   , tokenizer=_lowerCAmelCase   , evaluate=_lowerCAmelCase   , cache_dir=model_args.cache_dir     )
           if training_args.do_eval
           else None
       )
       if config.model_type == "xlnet":
              lowercase__			:		List[Any]       =	DataCollatorForPermutationLanguageModeling(
                  tokenizer=_lowerCAmelCase   , plm_probability=data_args.plm_probability   , max_span_length=data_args.max_span_length   , )
       else:
              if data_args.mlm and data_args.whole_word_mask:
                     lowercase__			:		List[str]       =	DataCollatorForWholeWordMask(
                         tokenizer=_lowerCAmelCase   , mlm_probability=data_args.mlm_probability     )
              else:
                     lowercase__			:		str       =	DataCollatorForLanguageModeling(
                         tokenizer=_lowerCAmelCase   , mlm=data_args.mlm   , mlm_probability=data_args.mlm_probability     )

    # Initialize our Trainer
       lowercase__			:		Optional[int]       =	Trainer(
           model=_lowerCAmelCase   , args=_lowerCAmelCase   , data_collator=_lowerCAmelCase   , train_dataset=_lowerCAmelCase   , eval_dataset=_lowerCAmelCase   , prediction_loss_only=_lowerCAmelCase   , )

       # Training
       if training_args.do_train:
              lowercase__			:		List[str]       =	(
                  model_args.model_name_or_path
                  if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path     )
                  else None
              )
              trainer.train(model_path=_lowerCAmelCase     )
              trainer.save_model()
              # For convenience, we also re-save the tokenizer to the same directory,
              # so that you can share your model easily on huggingface.co/models =)
              if trainer.is_world_master():
                     tokenizer.save_pretrained(training_args.output_dir     )

    # Evaluation
       lowercase__			:		List[Any]       =	{}
       if training_args.do_eval:
              logger.info('*** Evaluate ***'     )

              lowercase__			:		Dict       =	trainer.evaluate()

              lowercase__			:		List[Any]       =	math.exp(eval_output['eval_loss']     )
              lowercase__			:		int       =	{'perplexity': perplexity}

              lowercase__			:		int       =	os.path.join(training_args.output_dir   , 'eval_results_lm.txt'     )
              if trainer.is_world_master():
                     with open(_lowerCAmelCase   , 'w'     ) as writer:
                            logger.info('***** Eval results *****'     )
                            for key in sorted(result.keys()     ):
                                   logger.info('  %s = %s'   , _lowerCAmelCase   , str(result[key]     )     )
                                   writer.write('%s = %s\n' % (key, str(result[key]     ))     )

              results.update(_lowerCAmelCase     )

       return results





def 				a_     (      _lowerCAmelCase  : Optional[Any]     ):





       '''simple docstring'''

       main()


if __name__ == "__main__":
       main()





import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
     import torch
     from torch import nn

     from transformers import RegNetForImageClassification, RegNetModel
     from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor






class   _lowerCamelCase :




       """simple docstring"""



       def __init__(      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=3				,       _SCREAMING_SNAKE_CASE=32				,       _SCREAMING_SNAKE_CASE=3				,       _SCREAMING_SNAKE_CASE=10				,       _SCREAMING_SNAKE_CASE=[10, 20, 30, 40]				,       _SCREAMING_SNAKE_CASE=[1, 1, 2, 1]				,       _SCREAMING_SNAKE_CASE=True				,       _SCREAMING_SNAKE_CASE=True				,       _SCREAMING_SNAKE_CASE="relu"				,       _SCREAMING_SNAKE_CASE=3				,       _SCREAMING_SNAKE_CASE=None				,       )->List[str]:




         '''simple docstring'''





         A_      :				str		     =					parent
         A_      :				int		     =					batch_size
         A_      :				List[str]		     =					image_size
         A_      :				Dict		     =					num_channels
         A_      :				Tuple		     =					embeddings_size
         A_      :				Union[str, Any]		     =					hidden_sizes
         A_      :				Dict		     =					depths
         A_      :				str		     =					is_training
         A_      :				Union[str, Any]		     =					use_labels
         A_      :				Union[str, Any]		     =					hidden_act
         A_      :				Optional[Any]		     =					num_labels
         A_      :				Tuple		     =					scope
         A_      :				Optional[int]		     =					len(_SCREAMING_SNAKE_CASE		)



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




         '''simple docstring'''





         A_      :				List[str]		     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

         A_      :				str		     =					None
         if self.use_labels:
           A_      :				Union[str, Any]		     =					ids_tensor([self.batch_size]				,       self.num_labels		)

         A_      :				Optional[Any]		     =					self.get_config()

         return config, pixel_values, labels



       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         return RegNetConfig(
             num_channels=self.num_channels				,       embeddings_size=self.embeddings_size				,       hidden_sizes=self.hidden_sizes				,       depths=self.depths				,       hidden_act=self.hidden_act				,       num_labels=self.num_labels				,       )



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Dict		     =					RegNetModel(config=_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				Any		     =					model(_SCREAMING_SNAKE_CASE		)
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape				,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,       )



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Union[str, Any]		     =					self.num_labels
         A_      :				Dict		     =					RegNetForImageClassification(_SCREAMING_SNAKE_CASE		)
         model.to(_SCREAMING_SNAKE_CASE		)
         model.eval()
         A_      :				int		     =					model(_SCREAMING_SNAKE_CASE				,       labels=_SCREAMING_SNAKE_CASE		)
         self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)		)







       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Tuple		     =					self.prepare_config_and_inputs()
         A_     ,       A_     ,       A_      :				str		     =					config_and_inputs
         A_      :				Any		     =					{'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
class   _lowerCamelCase (					UpperCamelCase					,							UpperCamelCase					,							unittest.TestCase			):




       """simple docstring"""
       snake_case      =    (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       snake_case      =    (
           {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       snake_case      =    False
       snake_case      =    False
       snake_case      =    False
       snake_case      =    False



       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Union[str, Any]		     =					RegNetModelTester(self		)
         A_      :				Union[str, Any]		     =					ConfigTester(self				,       config_class=_SCREAMING_SNAKE_CASE				,       has_text_modality=_SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()



       def        _snake_case       (      self		)->Tuple:




         '''simple docstring'''





         return



       @unittest.skip(reason='''RegNet does not use inputs_embeds'''		)
       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         pass



       @unittest.skip(reason='''RegNet does not support input and output embeddings'''		)
       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         pass



       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         A_     ,       A_      :				Optional[Any]		     =					self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           A_      :				str		     =					model_class(_SCREAMING_SNAKE_CASE		)
           A_      :				Union[str, Any]		     =					inspect.signature(model.forward		)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           A_      :				Any		     =					[*signature.parameters.keys()]

           A_      :				Any		     =					['''pixel_values''']
           self.assertListEqual(arg_names[:1]				,       _SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





         A_      :				Dict		     =					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)



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




         '''simple docstring'''





         A_     ,       A_      :				int		     =					self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           A_      :				Union[str, Any]		     =					model_class(config=_SCREAMING_SNAKE_CASE		)
           for name, module in model.named_modules():
             if isinstance(_SCREAMING_SNAKE_CASE				,       (nn.BatchNormad, nn.GroupNorm)		):
               self.assertTrue(
                   torch.all(module.weight == 1		)				,       msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''				,       )
               self.assertTrue(
                   torch.all(module.bias == 0		)				,       msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''				,       )



       def        _snake_case       (      self		)->List[Any]:




         '''simple docstring'''





         def check_hidden_states_output(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		):
           A_      :				str		     =					model_class(_SCREAMING_SNAKE_CASE		)
           model.to(_SCREAMING_SNAKE_CASE		)
           model.eval()

           with torch.no_grad():
             A_      :				Tuple		     =					model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)		)

           A_      :				Union[str, Any]		     =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           A_      :				Optional[int]		     =					self.model_tester.num_stages
           self.assertEqual(len(_SCREAMING_SNAKE_CASE		)				,       expected_num_stages + 1		)

           # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
           self.assertListEqual(
               list(hidden_states[0].shape[-2:]		)				,       [self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,       )

         A_     ,       A_      :				Tuple		     =					self.model_tester.prepare_config_and_inputs_for_common()
         A_      :				int		     =					['''basic''', '''bottleneck''']
         for model_class in self.all_model_classes:
           for layer_type in layers_type:
             A_      :				int		     =					layer_type
             A_      :				List[Any]		     =					True
             check_hidden_states_output(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             A_      :				str		     =					True

             check_hidden_states_output(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)



       def        _snake_case       (      self		)->Dict:




         '''simple docstring'''





         A_      :				List[str]		     =					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE		)







       @slow
       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           A_      :				Dict		     =					RegNetModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
           self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)




def   _SCREAMING_SNAKE_CASE	( ):
  A_      :				int		     =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
  return image







@require_torch
@require_vision
class   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       @cached_property
       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         return (
             AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
             if is_vision_available()
             else None
         )







       @slow
       def        _snake_case       (      self		)->Tuple:




         '''simple docstring'''





         A_      :				List[Any]		     =					RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_SCREAMING_SNAKE_CASE		)

         A_      :				Optional[Any]		     =					self.default_image_processor
         A_      :				Any		     =					prepare_img()
         A_      :				Optional[Any]		     =					image_processor(images=_SCREAMING_SNAKE_CASE				,       return_tensors='''pt'''		).to(_SCREAMING_SNAKE_CASE		)

         # forward pass
         with torch.no_grad():
           A_      :				Union[str, Any]		     =					model(**_SCREAMING_SNAKE_CASE		)

         # verify the logits
         A_      :				Union[str, Any]		     =					torch.Size((1, 1000)		)
         self.assertEqual(outputs.logits.shape				,       _SCREAMING_SNAKE_CASE		)

         A_      :				Optional[int]		     =					torch.tensor([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]		).to(_SCREAMING_SNAKE_CASE		)

         self.assertTrue(torch.allclose(outputs.logits[0, :3]				,       _SCREAMING_SNAKE_CASE				,       atol=1e-4		)		)




