

"""simple docstring"""




import os
import re
import shutil
from argparse import ArgumentParser, Namespace

from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger


SCREAMING_SNAKE_CASE_     :			str	  =			'''<<<<<<< This should probably be modified because it mentions: '''

SCREAMING_SNAKE_CASE_     :			List[Any]	  =			'''=======
>>>>>>>
'''

SCREAMING_SNAKE_CASE_     :			List[str]	  =			[
    '''TextEncoderConfig''',
    '''ByteTextEncoder''',
    '''SubwordTextEncoder''',
    '''encoder_config''',
    '''maybe_build_from_corpus''',
    '''manual_dir''',
]

SCREAMING_SNAKE_CASE_     :			int	  =			[
    # (pattern, replacement)
    # Order is important here for some replacements
    (r'''tfds\.core''', r'''datasets'''),
    (r'''tf\.io\.gfile\.GFile''', r'''open'''),
    (r'''tf\.([\w\d]+)''', r'''datasets.Value(\'\1\')'''),
    (r'''tfds\.features\.Text\(\)''', r'''datasets.Value(\'string\')'''),
    (r'''tfds\.features\.Text\(''', r'''datasets.Value(\'string\'),'''),
    (r'''features\s*=\s*tfds.features.FeaturesDict\(''', r'''features=datasets.Features('''),
    (r'''tfds\.features\.FeaturesDict\(''', r'''dict('''),
    (r'''The TensorFlow Datasets Authors''', r'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''),
    (r'''tfds\.''', r'''datasets.'''),
    (r'''dl_manager\.manual_dir''', r'''self.config.data_dir'''),
    (r'''self\.builder_config''', r'''self.config'''),
]



def 	UpperCAmelCase__   (				A__   )      ->      str:




   """simple docstring"""
   return ConvertCommand(args.tfds_path	,    args.datasets_directory   )


class 		_A       (			__a					):





      @staticmethod
      def 					_lowerCamelCase  (  SCREAMING_SNAKE_CASE__		)   ->					int:
         lowerCamelCase__						=			parser.add_parser(
             "convert"    ,						help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset."    ,						)
         train_parser.add_argument(
             "--tfds_path"    ,						type=SCREAMING_SNAKE_CASE__    ,						required=SCREAMING_SNAKE_CASE__    ,						help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert."    ,						)
         train_parser.add_argument(
             "--datasets_directory"    ,						type=SCREAMING_SNAKE_CASE__    ,						required=SCREAMING_SNAKE_CASE__    ,						help="Path to the HuggingFace Datasets folder."		)
         train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__		)





      def __init__(  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						*SCREAMING_SNAKE_CASE__		)   ->					Union[str, Any]:
         lowerCamelCase__						=			get_logger("datasets-cli/converting"		)

         lowerCamelCase__						=			tfds_path
         lowerCamelCase__						=			datasets_directory





      def 					_lowerCamelCase  (  self		)   ->					Optional[int]:
         if os.path.isdir(self._tfds_path		):
            lowerCamelCase__						=			os.path.abspath(self._tfds_path		)
         elif os.path.isfile(self._tfds_path		):
            lowerCamelCase__						=			os.path.dirname(self._tfds_path		)
         else:
            raise ValueError("--tfds_path is neither a directory nor a file. Please check path."		)

         lowerCamelCase__						=			os.path.abspath(self._datasets_directory		)

         self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}'		)

         lowerCamelCase__						=			[]
         lowerCamelCase__						=			[]
         lowerCamelCase__						=			{}

         if os.path.isdir(self._tfds_path		):
            lowerCamelCase__						=			os.listdir(SCREAMING_SNAKE_CASE__		)
         else:
            lowerCamelCase__						=			[os.path.basename(self._tfds_path		)]

         for f_name in file_names:
            self._logger.info(f'Looking at file {f_name}'		)
            lowerCamelCase__						=			os.path.join(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)
            lowerCamelCase__						=			os.path.join(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)

            if not os.path.isfile(SCREAMING_SNAKE_CASE__		) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
               self._logger.info("Skipping file"		)
               continue

            with open(SCREAMING_SNAKE_CASE__    ,						encoding="utf-8"		) as f:
               lowerCamelCase__						=			f.readlines()

            lowerCamelCase__						=			[]
            lowerCamelCase__						=			False
            lowerCamelCase__						=			False
            lowerCamelCase__						=			[]
            for line in lines:
               lowerCamelCase__						=			line

               # Convert imports
               if "import tensorflow.compat.v2 as tf" in out_line:
                  continue
               elif "@tfds.core" in out_line:
                  continue
               elif "builder=self" in out_line:
                  continue
               elif "import tensorflow_datasets.public_api as tfds" in out_line:
                  lowerCamelCase__						=			"import datasets\n"
               elif "import tensorflow" in out_line:
                  # order is important here
                  lowerCamelCase__						=			""
                  continue
               elif "from absl import logging" in out_line:
                  lowerCamelCase__						=			"from datasets import logging\n"
               elif "getLogger" in out_line:
                  lowerCamelCase__						=			out_line.replace("getLogger"    ,						"get_logger"		)
               elif any(expression in out_line for expression in TO_HIGHLIGHT		):
                  lowerCamelCase__						=			True
                  lowerCamelCase__						=			list(filter(lambda SCREAMING_SNAKE_CASE__		: e in out_line    ,						SCREAMING_SNAKE_CASE__		)		)
                  out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(SCREAMING_SNAKE_CASE__		) + "\n"		)
                  out_lines.append(SCREAMING_SNAKE_CASE__		)
                  out_lines.append(SCREAMING_SNAKE_CASE__		)
                  continue
               else:
                  for pattern, replacement in TO_CONVERT:
                     lowerCamelCase__						=			re.sub(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)

                # Take care of saving utilities (to later move them together with main script)
               if "tensorflow_datasets" in out_line:
                  lowerCamelCase__						=			re.match(r"from\stensorflow_datasets.*import\s([^\.\r\n]+)"    ,						SCREAMING_SNAKE_CASE__		)
                  tfds_imports.extend(imp.strip() for imp in match.group(1		).split(","		)		)
                  lowerCamelCase__						=			"from . import " + match.group(1		)

               # Check we have not forget anything
               if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
                  raise ValueError(f'Error converting {out_line.strip()}'		)

               if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
                  lowerCamelCase__						=			True
               out_lines.append(SCREAMING_SNAKE_CASE__		)

            if is_builder or "wmt" in f_name:
               # We create a new directory for each dataset
               lowerCamelCase__						=			f_name.replace(".py"    ,						""		)
               lowerCamelCase__						=			os.path.join(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)
               lowerCamelCase__						=			os.path.join(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)
               os.makedirs(SCREAMING_SNAKE_CASE__    ,						exist_ok=SCREAMING_SNAKE_CASE__		)
               self._logger.info(f'Adding directory {output_dir}'		)
               imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}		)
            else:
               # Utilities will be moved at the end
               utils_files.append(SCREAMING_SNAKE_CASE__		)

            if needs_manual_update:
               with_manual_update.append(SCREAMING_SNAKE_CASE__		)

            with open(SCREAMING_SNAKE_CASE__    ,						"w"    ,						encoding="utf-8"		) as f:
               f.writelines(SCREAMING_SNAKE_CASE__		)
            self._logger.info(f'Converted in {output_file}'		)

         for utils_file in utils_files:
            try:
               lowerCamelCase__						=			os.path.basename(SCREAMING_SNAKE_CASE__		)
               lowerCamelCase__						=			imports_to_builder_map[f_name.replace(".py"    ,						""		)]
               self._logger.info(f'Moving {dest_folder} to {utils_file}'		)
               shutil.copy(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)
            except KeyError:
               self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.'		)

         if with_manual_update:
            for file_path in with_manual_update:
               self._logger.warning(
                   f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.'		)







"""simple docstring"""




import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer


class 		_A       :





      def __init__(  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__=13    ,						SCREAMING_SNAKE_CASE__=7    ,						SCREAMING_SNAKE_CASE__=True    ,						SCREAMING_SNAKE_CASE__=True    ,						SCREAMING_SNAKE_CASE__=False    ,						SCREAMING_SNAKE_CASE__=True    ,						SCREAMING_SNAKE_CASE__=99    ,						SCREAMING_SNAKE_CASE__=32    ,						SCREAMING_SNAKE_CASE__=5    ,						SCREAMING_SNAKE_CASE__=4    ,						SCREAMING_SNAKE_CASE__=37    ,						SCREAMING_SNAKE_CASE__="gelu"    ,						SCREAMING_SNAKE_CASE__=0.1    ,						SCREAMING_SNAKE_CASE__=0.1    ,						SCREAMING_SNAKE_CASE__=512    ,						SCREAMING_SNAKE_CASE__=16    ,						SCREAMING_SNAKE_CASE__=2    ,						SCREAMING_SNAKE_CASE__=0.02    ,						SCREAMING_SNAKE_CASE__=3    ,						SCREAMING_SNAKE_CASE__=4    ,						SCREAMING_SNAKE_CASE__=None    ,						)   ->					List[str]:
         lowerCamelCase__						=			parent
         lowerCamelCase__						=			batch_size
         lowerCamelCase__						=			seq_length
         lowerCamelCase__						=			is_training
         lowerCamelCase__						=			use_input_mask
         lowerCamelCase__						=			use_token_type_ids
         lowerCamelCase__						=			use_labels
         lowerCamelCase__						=			vocab_size
         lowerCamelCase__						=			hidden_size
         lowerCamelCase__						=			num_hidden_layers
         lowerCamelCase__						=			num_attention_heads
         lowerCamelCase__						=			intermediate_size
         lowerCamelCase__						=			hidden_act
         lowerCamelCase__						=			hidden_dropout_prob
         lowerCamelCase__						=			attention_probs_dropout_prob
         lowerCamelCase__						=			max_position_embeddings
         lowerCamelCase__						=			type_vocab_size
         lowerCamelCase__						=			type_sequence_label_size
         lowerCamelCase__						=			initializer_range
         lowerCamelCase__						=			num_labels
         lowerCamelCase__						=			num_choices
         lowerCamelCase__						=			scope





      def 					_lowerCamelCase  (  self		)   ->					Optional[Any]:
         lowerCamelCase__						=			ids_tensor([self.batch_size, self.seq_length]    ,						self.vocab_size		)

         lowerCamelCase__						=			None
         if self.use_input_mask:
            lowerCamelCase__						=			random_attention_mask([self.batch_size, self.seq_length]		)

         lowerCamelCase__						=			None
         if self.use_token_type_ids:
            lowerCamelCase__						=			ids_tensor([self.batch_size, self.seq_length]    ,						self.type_vocab_size		)

         lowerCamelCase__						=			None
         lowerCamelCase__						=			None
         lowerCamelCase__						=			None
         if self.use_labels:
            lowerCamelCase__						=			ids_tensor([self.batch_size]    ,						self.type_sequence_label_size		)
            lowerCamelCase__						=			ids_tensor([self.batch_size, self.seq_length]    ,						self.num_labels		)
            lowerCamelCase__						=			ids_tensor([self.batch_size]    ,						self.num_choices		)

         lowerCamelCase__						=			self.get_config()

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





      def 					_lowerCamelCase  (  self		)   ->					List[Any]:
         return LlamaConfig(
             vocab_size=self.vocab_size    ,						hidden_size=self.hidden_size    ,						num_hidden_layers=self.num_hidden_layers    ,						num_attention_heads=self.num_attention_heads    ,						intermediate_size=self.intermediate_size    ,						hidden_act=self.hidden_act    ,						hidden_dropout_prob=self.hidden_dropout_prob    ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,						max_position_embeddings=self.max_position_embeddings    ,						type_vocab_size=self.type_vocab_size    ,						is_decoder=SCREAMING_SNAKE_CASE__    ,						initializer_range=self.initializer_range    ,						)





      def 					_lowerCamelCase  (  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)   ->					int:
         lowerCamelCase__						=			LlamaModel(config=SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__		)
         self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)		)





      def 					_lowerCamelCase  (  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						)   ->					Any:
         lowerCamelCase__						=			True
         lowerCamelCase__						=			LlamaModel(SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(
             SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						encoder_hidden_states=SCREAMING_SNAKE_CASE__    ,						encoder_attention_mask=SCREAMING_SNAKE_CASE__    ,						)
         lowerCamelCase__						=			model(
             SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						encoder_hidden_states=SCREAMING_SNAKE_CASE__    ,						)
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__		)
         self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)		)





      def 					_lowerCamelCase  (  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						)   ->					str:
         lowerCamelCase__						=			LlamaForCausalLM(config=SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						labels=SCREAMING_SNAKE_CASE__		)
         self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.vocab_size)		)





      def 					_lowerCamelCase  (  self    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						)   ->					Union[str, Any]:
         lowerCamelCase__						=			True
         lowerCamelCase__						=			True
         lowerCamelCase__						=			LlamaForCausalLM(config=SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()

         # first forward pass
         lowerCamelCase__						=			model(
             SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						encoder_hidden_states=SCREAMING_SNAKE_CASE__    ,						encoder_attention_mask=SCREAMING_SNAKE_CASE__    ,						use_cache=SCREAMING_SNAKE_CASE__    ,						)
         lowerCamelCase__						=			outputs.past_key_values

         # create hypothetical multiple next token and extent to next_input_ids
         lowerCamelCase__						=			ids_tensor((self.batch_size, 3)    ,						config.vocab_size		)
         lowerCamelCase__						=			ids_tensor((self.batch_size, 3)    ,						vocab_size=2		)

         # append to next input_ids and
         lowerCamelCase__						=			torch.cat([input_ids, next_tokens]    ,						dim=-1		)
         lowerCamelCase__						=			torch.cat([input_mask, next_mask]    ,						dim=-1		)

         lowerCamelCase__						=			model(
             SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						encoder_hidden_states=SCREAMING_SNAKE_CASE__    ,						encoder_attention_mask=SCREAMING_SNAKE_CASE__    ,						output_hidden_states=SCREAMING_SNAKE_CASE__    ,						)["hidden_states"][0]
         lowerCamelCase__						=			model(
             SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						encoder_hidden_states=SCREAMING_SNAKE_CASE__    ,						encoder_attention_mask=SCREAMING_SNAKE_CASE__    ,						past_key_values=SCREAMING_SNAKE_CASE__    ,						output_hidden_states=SCREAMING_SNAKE_CASE__    ,						)["hidden_states"][0]

         # select random slice
         lowerCamelCase__						=			ids_tensor((1,)    ,						output_from_past.shape[-1]		).item()
         lowerCamelCase__						=			output_from_no_past[:, -3:, random_slice_idx].detach()
         lowerCamelCase__						=			output_from_past[:, :, random_slice_idx].detach()

         self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]		)

         # test that outputs are equal for slice
         self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-3		)		)





      def 					_lowerCamelCase  (  self		)   ->					Any:
         lowerCamelCase__						=			self.prepare_config_and_inputs()
         (
             (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       (
             lowerCamelCase__
         )					,       
         )						=			config_and_inputs
         lowerCamelCase__						=			{"input_ids": input_ids, "attention_mask": input_mask}
         return config, inputs_dict






@require_torch
class 		_A       (			__a				,       __a				,       __a				,       unittest.TestCase					):
      __a								=	(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
      __a								=	(LlamaForCausalLM,) if is_torch_available() else ()
      __a								=	(
          {
              'feature-extraction': LlamaModel,
              'text-classification': LlamaForSequenceClassification,
              'text-generation': LlamaForCausalLM,
              'zero-shot': LlamaForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      __a								=	False
      __a								=	False





      def 					_lowerCamelCase  (  self		)   ->					Tuple:
         lowerCamelCase__						=			LlamaModelTester(self		)
         lowerCamelCase__						=			ConfigTester(self    ,						config_class=SCREAMING_SNAKE_CASE__    ,						hidden_size=37		)





      def 					_lowerCamelCase  (  self		)   ->					List[str]:
         self.config_tester.run_common_tests()





      def 					_lowerCamelCase  (  self		)   ->					Tuple:
         lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__		)





      def 					_lowerCamelCase  (  self		)   ->					Optional[Any]:
         lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
            lowerCamelCase__						=			type
            self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__		)





      def 					_lowerCamelCase  (  self		)   ->					Union[str, Any]:
         lowerCamelCase__					,       lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs_for_common()
         lowerCamelCase__						=			3
         lowerCamelCase__						=			input_dict["input_ids"]
         lowerCamelCase__						=			input_ids.ne(1		).to(SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						=			ids_tensor([self.model_tester.batch_size]    ,						self.model_tester.type_sequence_label_size		)
         lowerCamelCase__						=			LlamaForSequenceClassification(SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						labels=SCREAMING_SNAKE_CASE__		)
         self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)		)





      def 					_lowerCamelCase  (  self		)   ->					Dict:
         lowerCamelCase__					,       lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs_for_common()
         lowerCamelCase__						=			3
         lowerCamelCase__						=			"single_label_classification"
         lowerCamelCase__						=			input_dict["input_ids"]
         lowerCamelCase__						=			input_ids.ne(1		).to(SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						=			ids_tensor([self.model_tester.batch_size]    ,						self.model_tester.type_sequence_label_size		)
         lowerCamelCase__						=			LlamaForSequenceClassification(SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						labels=SCREAMING_SNAKE_CASE__		)
         self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)		)





      def 					_lowerCamelCase  (  self		)   ->					Any:
         lowerCamelCase__					,       lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs_for_common()
         lowerCamelCase__						=			3
         lowerCamelCase__						=			"multi_label_classification"
         lowerCamelCase__						=			input_dict["input_ids"]
         lowerCamelCase__						=			input_ids.ne(1		).to(SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						=			ids_tensor(
             [self.model_tester.batch_size, config.num_labels]    ,						self.model_tester.type_sequence_label_size		).to(torch.float		)
         lowerCamelCase__						=			LlamaForSequenceClassification(SCREAMING_SNAKE_CASE__		)
         model.to(SCREAMING_SNAKE_CASE__		)
         model.eval()
         lowerCamelCase__						=			model(SCREAMING_SNAKE_CASE__    ,						attention_mask=SCREAMING_SNAKE_CASE__    ,						labels=SCREAMING_SNAKE_CASE__		)
         self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)		)





      @unittest.skip("LLaMA buffers include complex numbers, which breaks this test"		)
      def 					_lowerCamelCase  (  self		)   ->					List[Any]:
         pass





      @parameterized.expand([("linear",), ("dynamic",)]		)
      def 					_lowerCamelCase  (  self    ,						SCREAMING_SNAKE_CASE__		)   ->					Union[str, Any]:
         lowerCamelCase__					,       lowerCamelCase__						=			self.model_tester.prepare_config_and_inputs_for_common()
         lowerCamelCase__						=			ids_tensor([1, 10]    ,						config.vocab_size		)
         lowerCamelCase__						=			ids_tensor([1, int(config.max_position_embeddings * 1.5		)]    ,						config.vocab_size		)

         set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
         lowerCamelCase__						=			LlamaModel(SCREAMING_SNAKE_CASE__		)
         original_model.to(SCREAMING_SNAKE_CASE__		)
         original_model.eval()
         lowerCamelCase__						=			original_model(SCREAMING_SNAKE_CASE__		).last_hidden_state
         lowerCamelCase__						=			original_model(SCREAMING_SNAKE_CASE__		).last_hidden_state

         set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
         lowerCamelCase__						=			{"type": scaling_type, "factor": 10.0}
         lowerCamelCase__						=			LlamaModel(SCREAMING_SNAKE_CASE__		)
         scaled_model.to(SCREAMING_SNAKE_CASE__		)
         scaled_model.eval()
         lowerCamelCase__						=			scaled_model(SCREAMING_SNAKE_CASE__		).last_hidden_state
         lowerCamelCase__						=			scaled_model(SCREAMING_SNAKE_CASE__		).last_hidden_state

         # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
         # maximum sequence length, so the outputs for the short input should match.
         if scaling_type == "dynamic":
            self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5		)		)
         else:
            self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5		)		)

         # The output should be different for long inputs
         self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5		)		)






@require_torch
class 		_A       (			unittest.TestCase					):





      @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"		)
      @slow
      def 					_lowerCamelCase  (  self		)   ->					Optional[Any]:
         lowerCamelCase__						=			[1, 306, 4658, 278, 6593, 310, 2834, 338]
         lowerCamelCase__						=			LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf"    ,						device_map="auto"		)
         lowerCamelCase__						=			model(torch.tensor([input_ids]		)		)
         # Expected mean on dim = -1
         lowerCamelCase__						=			torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]]		)
         torch.testing.assert_close(out.mean(-1		)    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-2    ,						rtol=1e-2		)
         # slicing logits[0, 0, 0:30]
         # fmt: off
         lowerCamelCase__						=			torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,]		)
         # fmt: on
         torch.testing.assert_close(out[0, 0, :30]    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5    ,						rtol=1e-5		)





      @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"		)
      @slow
      def 					_lowerCamelCase  (  self		)   ->					Optional[Any]:
         lowerCamelCase__						=			[1, 306, 4658, 278, 6593, 310, 2834, 338]
         lowerCamelCase__						=			LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf"    ,						device_map="auto"		)
         lowerCamelCase__						=			model(torch.tensor(SCREAMING_SNAKE_CASE__		)		)
         # Expected mean on dim = -1
         lowerCamelCase__						=			torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]]		)
         torch.testing.assert_close(out.mean(-1		)    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-2    ,						rtol=1e-2		)
         # slicing logits[0, 0, 0:30]
         # fmt: off
         lowerCamelCase__						=			torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73]		)
         # fmt: on
         torch.testing.assert_close(out[0, 0, :30]    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5    ,						rtol=1e-5		)





      @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"		)
      @slow
      def 					_lowerCamelCase  (  self		)   ->					Optional[int]:
         lowerCamelCase__						=			[1, 306, 4658, 278, 6593, 310, 2834, 338]
         lowerCamelCase__						=			LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf"    ,						device_map="auto"		)
         lowerCamelCase__						=			model(torch.tensor(SCREAMING_SNAKE_CASE__		)		)
         # Expected mean on dim = -1
         lowerCamelCase__						=			torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]]		)
         torch.testing.assert_close(out.mean(-1		)    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-2    ,						rtol=1e-2		)
         # slicing logits[0, 0, 0:30]
         # fmt: off
         lowerCamelCase__						=			torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13]		)
         # fmt: on
         torch.testing.assert_close(out.mean(-1		)    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-2    ,						rtol=1e-2		)





      @unittest.skip(
          "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test"		)
      @slow
      def 					_lowerCamelCase  (  self		)   ->					List[str]:
         lowerCamelCase__						=			[1, 306, 4658, 278, 6593, 310, 2834, 338]
         lowerCamelCase__						=			LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-70b-hf"    ,						device_map="auto"		)
         lowerCamelCase__						=			model(torch.tensor(SCREAMING_SNAKE_CASE__		)		)

         lowerCamelCase__						=			torch.tensor(
             [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]]    ,						dtype=torch.floataa		)
         torch.testing.assert_close(out.mean(-1		)    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-2    ,						rtol=1e-2		)
         # fmt: off
         lowerCamelCase__						=			torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12]		)
         # fmt: on
         torch.testing.assert_close(out[0, 0, :30]    ,						SCREAMING_SNAKE_CASE__    ,						atol=1e-5    ,						rtol=1e-5		)





      @unittest.skip("Model is curently gated"		)
      @slow
      def 					_lowerCamelCase  (  self		)   ->					List[Any]:
         lowerCamelCase__						=			"Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi"
         lowerCamelCase__						=			"Simply put, the theory of relativity states that "
         lowerCamelCase__						=			LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf"		)
         lowerCamelCase__						=			tokenizer.encode(SCREAMING_SNAKE_CASE__    ,						return_tensors="pt"		)
         lowerCamelCase__						=			LlamaForCausalLM.from_pretrained(
             "meta-llama/Llama-2-13b-chat-hf"    ,						device_map="sequential"    ,						use_safetensors=SCREAMING_SNAKE_CASE__		)

         # greedy generation outputs
         lowerCamelCase__						=			model.generate(SCREAMING_SNAKE_CASE__    ,						max_new_tokens=64    ,						top_p=SCREAMING_SNAKE_CASE__    ,						temperature=1    ,						do_sample=SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						=			tokenizer.decode(generated_ids[0]    ,						skip_special_tokens=SCREAMING_SNAKE_CASE__		)
         self.assertEqual(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__		)




