




import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
SCREAMING_SNAKE_CASE__       :      Union[str, Any]  =   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__       :      List[Any]  =   {
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
}
SCREAMING_SNAKE_CASE__       :      Tuple  =   [
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
]

def      A      (      _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )	-> Optional[Any]:
       for attribute in key.split("."    ):
              lowerCamelCase   :      Dict			 =					getattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )

       if weight_type is not None:
              lowerCamelCase   :      List[str]			 =					getattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    ).shape
       else:
              lowerCamelCase   :      Union[str, Any]			 =					hf_pointer.shape

       assert hf_shape == value.shape, (
           f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
           f''' {value.shape} for {full_name}'''
       )

       if weight_type == "weight":
              lowerCamelCase   :      Optional[Any]			 =					value
       elif weight_type == "weight_g":
              lowerCamelCase   :      Optional[Any]			 =					value
       elif weight_type == "weight_v":
              lowerCamelCase   :      str			 =					value
       elif weight_type == "bias":
              lowerCamelCase   :      Union[str, Any]			 =					value
       else:
              lowerCamelCase   :      Dict			 =					value

       logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''    )

def      A      (      _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )	-> Dict:
       lowerCamelCase   :      Optional[int]			 =					[]
       lowerCamelCase   :      Optional[Any]			 =					fairseq_model.state_dict()

       lowerCamelCase   :      Dict			 =					hf_model.feature_extractor

       # if encoder has different dim to decoder -> use proj_weight
       lowerCamelCase   :      str			 =					None

       for name, value in fairseq_dict.items():
              lowerCamelCase   :      str			 =					False
              if "conv_layers" in name:
                     load_conv_layer(
                         _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,hf_model.config.feat_extract_norm == "group" ,)
                     lowerCamelCase   :      Union[str, Any]			 =					True
              elif name.split("."    )[0] == "proj":
                     lowerCamelCase   :      List[str]			 =					fairseq_model.proj
                     lowerCamelCase   :      Optional[Any]			 =					True
              else:
                     for key, mapped_key in MAPPING.items():
                            if key in name or key.split("w2v_model."    )[-1] == name.split("."    )[0]:
                                   lowerCamelCase   :      int			 =					True
                                   if "*" in mapped_key:
                                          lowerCamelCase   :      Union[str, Any]			 =					name.split(_SCREAMING_SNAKE_CASE    )[0].split("."    )[-2]
                                          lowerCamelCase   :      List[str]			 =					mapped_key.replace("*" ,_SCREAMING_SNAKE_CASE    )
                                   if "weight_g" in name:
                                          lowerCamelCase   :      Optional[int]			 =					"weight_g"
                                   elif "weight_v" in name:
                                          lowerCamelCase   :      int			 =					"weight_v"
                                   elif "bias" in name:
                                          lowerCamelCase   :      int			 =					"bias"
                                   elif "weight" in name:
                                          lowerCamelCase   :      List[str]			 =					"weight"
                                   else:
                                          lowerCamelCase   :      Dict			 =					None
                                   set_recursively(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )
                            continue
              if not is_used:
                     unused_weights.append(_SCREAMING_SNAKE_CASE    )

       logger.warning(f'''Unused weights: {unused_weights}'''    )

       return proj_weight

def      A      (      _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )	-> str:
       lowerCamelCase   :      List[Any]			 =					full_name.split("conv_layers."    )[-1]
       lowerCamelCase   :      Any			 =					name.split("."    )
       lowerCamelCase   :      int			 =					int(items[0]    )
       lowerCamelCase   :      Tuple			 =					int(items[1]    )

       if type_id == 0:
              if "bias" in name:
                     assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                         f'''{full_name} has size {value.shape}, but'''
                         f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
                     )
                     lowerCamelCase   :      int			 =					value
                     logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''    )
              elif "weight" in name:
                     assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                         f'''{full_name} has size {value.shape}, but'''
                         f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
                     )
                     lowerCamelCase   :      Dict			 =					value
                     logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''    )
       elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
              if "bias" in name:
                     assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                         f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
                         " found."
                     )
                     lowerCamelCase   :      Dict			 =					value
                     logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''    )
              elif "weight" in name:
                     assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                         f'''{full_name} has size {value.shape}, but'''
                         f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
                     )
                     lowerCamelCase   :      List[Any]			 =					value
                     logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''    )
       else:
              unused_weights.append(_SCREAMING_SNAKE_CASE    )

def      A      (      _SCREAMING_SNAKE_CASE    )	-> str:
       lowerCamelCase ,      lowerCamelCase   :      List[str]			 =					emb.weight.shape
       lowerCamelCase   :      int			 =					nn.Linear(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,bias=_SCREAMING_SNAKE_CASE    )
       lowerCamelCase   :      Optional[int]			 =					emb.weight.data
       return lin_layer

def      A      (      _SCREAMING_SNAKE_CASE    )	-> Dict:
       with open(_SCREAMING_SNAKE_CASE ,"r" ,encoding="utf-8"    ) as f:
              lowerCamelCase   :      Union[str, Any]			 =					f.readlines()
              lowerCamelCase   :      Optional[int]			 =					[line.split(" "    )[0] for line in lines]

       lowerCamelCase   :      Dict			 =					len(_SCREAMING_SNAKE_CASE    )

       lowerCamelCase   :      List[str]			 =					{
           "<s>": 0,
           "<pad>": 1,
           "</s>": 2,
           "<unk>": 3,
       }

       vocab_dict.update(dict(zip(_SCREAMING_SNAKE_CASE ,range(4 ,num_words + 4    )    )    )    )
       return vocab_dict

@torch.no_grad()
def      A      (      _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,)	-> Optional[int]:
       lowerCamelCase   :      Dict			 =					WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE    )
       lowerCamelCase   :      Tuple			 =					SpeechaTextaConfig.from_pretrained(
           _SCREAMING_SNAKE_CASE ,vocab_size=_SCREAMING_SNAKE_CASE ,decoder_layers=_SCREAMING_SNAKE_CASE ,do_stable_layer_norm=_SCREAMING_SNAKE_CASE    )

       lowerCamelCase   :      str			 =					WavaVecaFeatureExtractor(
           feature_size=1 ,sampling_rate=1_6000 ,padding_value=0 ,do_normalize=_SCREAMING_SNAKE_CASE ,return_attention_mask=_SCREAMING_SNAKE_CASE ,)

       lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase   :      Optional[int]			 =					fairseq.checkpoint_utils.load_model_ensemble_and_task(
           [checkpoint_path] ,arg_overrides={"data": "/".join(dict_path.split("/"    )[:-1]    )}    )
       lowerCamelCase   :      int			 =					model[0].eval()

       # set weights for wav2vec2 encoder
       lowerCamelCase   :      str			 =					WavaVecaModel(_SCREAMING_SNAKE_CASE    )
       lowerCamelCase   :      Dict			 =					recursively_load_weights_wavaveca(model.encoder ,_SCREAMING_SNAKE_CASE    )

       lowerCamelCase   :      Any			 =					SpeechaTextaForCausalLM(_SCREAMING_SNAKE_CASE    )
       lowerCamelCase ,      lowerCamelCase   :      List[Any]			 =					hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() ,strict=_SCREAMING_SNAKE_CASE    )

       # set output linear layer
       unexpected_keys.remove("embed_out"    )
       lowerCamelCase   :      Dict			 =					nn.Parameter(model.decoder.embed_out.detach()    )

       # layer norm is init to identity matrix so leaving it is fine
       logger.warning(f'''The following keys are missing when loading the decoder weights: {missing_keys}'''    )
       logger.warning(f'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}'''    )

       lowerCamelCase   :      str			 =					SpeechEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE    )
       lowerCamelCase   :      Optional[int]			 =					False

       # add projection layer
       lowerCamelCase   :      List[Any]			 =					nn.Parameter(projection_layer.weight    )
       lowerCamelCase   :      Tuple			 =					nn.Parameter(projection_layer.bias    )

       lowerCamelCase   :      Dict			 =					create_vocab_dict(_SCREAMING_SNAKE_CASE    )

       with open(os.path.join(_SCREAMING_SNAKE_CASE ,"vocab.json"    ) ,"w"    ) as fp:
              json.dump(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )

       lowerCamelCase   :      Dict			 =					SpeechaTextaTokenizer(os.path.join(_SCREAMING_SNAKE_CASE ,"vocab.json"    )    )
       tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE    )

       lowerCamelCase   :      Optional[Any]			 =					hf_wavavec.config.to_dict()
       lowerCamelCase   :      str			 =					tokenizer.pad_token_id
       lowerCamelCase   :      List[Any]			 =					tokenizer.bos_token_id
       lowerCamelCase   :      List[Any]			 =					tokenizer.eos_token_id
       lowerCamelCase   :      str			 =					"speech_to_text_2"
       lowerCamelCase   :      Dict			 =					"wav2vec2"

       lowerCamelCase   :      Dict			 =					SpeechEncoderDecoderConfig.from_dict(_SCREAMING_SNAKE_CASE    )

       hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE    )
       feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE    )


if __name__ == "__main__":
       SCREAMING_SNAKE_CASE__       :      Optional[Any]  =   argparse.ArgumentParser()
       parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
       parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
       parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
       parser.add_argument(
           '--encoder_config_path',
           default='facebook/wav2vec2-large-lv60',
           type=str,
           help='Path to hf encoder wav2vec2 checkpoint config',
       )
       parser.add_argument(
           '--decoder_config_path',
           default='facebook/s2t-small-mustc-en-fr-st',
           type=str,
           help='Path to hf decoder s2t checkpoint config',
       )
       parser.add_argument('--vocab_size', default=10224, type=int, help='Vocab size of decoder')
       parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers')

       SCREAMING_SNAKE_CASE__       :      Tuple  =   parser.parse_args()
       convert_wavaveca_checkpoint(
           args.checkpoint_path,
           args.pytorch_dump_folder_path,
           args.dict_path,
           encoder_config_path=args.encoder_config_path,
           decoder_config_path=args.decoder_config_path,
           vocab_size=args.vocab_size,
           num_decoder_layers=args.num_decoder_layers,
       )










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						:     Union[str, Any]			,   lowercase_						:     Any			,   lowercase_						:     Dict=13			,   lowercase_						:     List[Any]=7			,   lowercase_						:     List[Any]=True			,   lowercase_						:     Any=True			,   lowercase_						:     Optional[int]=False			,   lowercase_						:     Tuple=True			,   lowercase_						:     List[str]=99			,   lowercase_						:     Union[str, Any]=32			,   lowercase_						:     List[Any]=5			,   lowercase_						:     Dict=4			,   lowercase_						:     List[Any]=37			,   lowercase_						:     Any="gelu"			,   lowercase_						:     Union[str, Any]=0.1			,   lowercase_						:     Tuple=0.1			,   lowercase_						:     List[Any]=512			,   lowercase_						:     Any=16			,   lowercase_						:     Optional[int]=2			,   lowercase_						:     Any=0.02			,   lowercase_						:     Dict=3			,   lowercase_						:     Union[str, Any]=4			,   lowercase_						:     Tuple=None			,   )					->						List[Any]:
             """simple docstring"""




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






      def        lowerCamelCase       (					self						:     Dict )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=ids_tensor([self.batch_size, self.seq_length]			,   self.vocab_size )

             _lowerCamelCase       :		Union[str, Any]		=None
             if self.use_input_mask:
                    _lowerCamelCase       :		Dict		=random_attention_mask([self.batch_size, self.seq_length] )

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

             _lowerCamelCase       :		Tuple		=None
             _lowerCamelCase       :		Optional[Any]		=None
             _lowerCamelCase       :		Optional[Any]		=None
             if self.use_labels:
                    _lowerCamelCase       :		int		=ids_tensor([self.batch_size]			,   self.type_sequence_label_size )
                    _lowerCamelCase       :		Union[str, Any]		=ids_tensor([self.batch_size, self.seq_length]			,   self.num_labels )
                    _lowerCamelCase       :		List[Any]		=ids_tensor([self.batch_size]			,   self.num_choices )

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

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






      def        lowerCamelCase       (					self						:     int )					->						Tuple:
             """simple docstring"""




             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=lowercase_			,   initializer_range=self.initializer_range			,   )






      def        lowerCamelCase       (					self						:     Tuple			,   lowercase_						:     Optional[int]			,   lowercase_						:     Tuple			,   lowercase_						:     List[Any]			,   lowercase_						:     str			,   lowercase_						:     Optional[Any]			,   lowercase_						:     Optional[int]			,   lowercase_						:     List[Any] )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		Dict		=LlamaModel(config=lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		List[str]		=model(lowercase_			,   attention_mask=lowercase_ )
             _lowerCamelCase       :		List[str]		=model(lowercase_ )
             self.parent.assertEqual(result.last_hidden_state.shape			,   (self.batch_size, self.seq_length, self.hidden_size) )






      def        lowerCamelCase       (					self						:     int			,   lowercase_						:     Tuple			,   lowercase_						:     Optional[int]			,   lowercase_						:     int			,   lowercase_						:     List[str]			,   lowercase_						:     Dict			,   lowercase_						:     Any			,   lowercase_						:     str			,   lowercase_						:     Dict			,   lowercase_						:     str			,   )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		str		=True
             _lowerCamelCase       :		str		=LlamaModel(lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		int		=model(
                 lowercase_			,   attention_mask=lowercase_			,   encoder_hidden_states=lowercase_			,   encoder_attention_mask=lowercase_			,   )
             _lowerCamelCase       :		str		=model(
                 lowercase_			,   attention_mask=lowercase_			,   encoder_hidden_states=lowercase_			,   )
             _lowerCamelCase       :		List[Any]		=model(lowercase_			,   attention_mask=lowercase_ )
             self.parent.assertEqual(result.last_hidden_state.shape			,   (self.batch_size, self.seq_length, self.hidden_size) )






      def        lowerCamelCase       (					self						:     Dict			,   lowercase_						:     Dict			,   lowercase_						:     List[Any]			,   lowercase_						:     Tuple			,   lowercase_						:     Dict			,   lowercase_						:     Tuple			,   lowercase_						:     str			,   lowercase_						:     List[Any]			,   lowercase_						:     List[Any]			,   lowercase_						:     Any			,   )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		int		=LlamaForCausalLM(config=lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		int		=model(lowercase_			,   attention_mask=lowercase_			,   labels=lowercase_ )
             self.parent.assertEqual(result.logits.shape			,   (self.batch_size, self.seq_length, self.vocab_size) )






      def        lowerCamelCase       (					self						:     int			,   lowercase_						:     str			,   lowercase_						:     Dict			,   lowercase_						:     str			,   lowercase_						:     Any			,   lowercase_						:     Optional[int]			,   lowercase_						:     List[Any]			,   lowercase_						:     str			,   lowercase_						:     Optional[int]			,   lowercase_						:     Optional[Any]			,   )					->						List[str]:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=True
             _lowerCamelCase       :		Tuple		=True
             _lowerCamelCase       :		str		=LlamaForCausalLM(config=lowercase_ )
             model.to(lowercase_ )
             model.eval()

             # first forward pass
             _lowerCamelCase       :		int		=model(
                 lowercase_			,   attention_mask=lowercase_			,   encoder_hidden_states=lowercase_			,   encoder_attention_mask=lowercase_			,   use_cache=lowercase_			,   )
             _lowerCamelCase       :		Any		=outputs.past_key_values

             # create hypothetical multiple next token and extent to next_input_ids
             _lowerCamelCase       :		Union[str, Any]		=ids_tensor((self.batch_size, 3)			,   config.vocab_size )
             _lowerCamelCase       :		Optional[Any]		=ids_tensor((self.batch_size, 3)			,   vocab_size=2 )

             # append to next input_ids and
             _lowerCamelCase       :		Tuple		=torch.cat([input_ids, next_tokens]			,   dim=-1 )
             _lowerCamelCase       :		Optional[Any]		=torch.cat([input_mask, next_mask]			,   dim=-1 )

             _lowerCamelCase       :		Optional[int]		=model(
                 lowercase_			,   attention_mask=lowercase_			,   encoder_hidden_states=lowercase_			,   encoder_attention_mask=lowercase_			,   output_hidden_states=lowercase_			,   )['hidden_states'][0]
             _lowerCamelCase       :		Tuple		=model(
                 lowercase_			,   attention_mask=lowercase_			,   encoder_hidden_states=lowercase_			,   encoder_attention_mask=lowercase_			,   past_key_values=lowercase_			,   output_hidden_states=lowercase_			,   )['hidden_states'][0]

             # select random slice
             _lowerCamelCase       :		int		=ids_tensor((1,)			,   output_from_past.shape[-1] ).item()
             _lowerCamelCase       :		Optional[Any]		=output_from_no_past[:, -3:, random_slice_idx].detach()
             _lowerCamelCase       :		Optional[int]		=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(lowercase_			,   lowercase_			,   atol=1E-3 ) )






      def        lowerCamelCase       (					self						:     Tuple )					->						str:
             """simple docstring"""




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




@require_torch
class A  (   UpperCamelCase_    ,							UpperCamelCase_    ,							UpperCamelCase_    ,							unittest.TestCase     ):
      UpperCamelCase__							:  Optional[Any]      =(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
      UpperCamelCase__							:  Union[str, Any]      =(LlamaForCausalLM,) if is_torch_available() else ()
      UpperCamelCase__							:  List[Any]      =(
          {
              'feature-extraction': LlamaModel,
              'text-classification': LlamaForSequenceClassification,
              'text-generation': LlamaForCausalLM,
              'zero-shot': LlamaForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      UpperCamelCase__							:  Optional[Any]      =False
      UpperCamelCase__							:  Tuple      =False






      def        lowerCamelCase       (					self						:     Union[str, Any] )					->						str:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=LlamaModelTester(self )
             _lowerCamelCase       :		Any		=ConfigTester(self			,   config_class=lowercase_			,   hidden_size=37 )






      def        lowerCamelCase       (					self						:     List[str] )					->						Tuple:
             """simple docstring"""




             self.config_tester.run_common_tests()






      def        lowerCamelCase       (					self						:     Dict )					->						str:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_ )






      def        lowerCamelCase       (					self						:     int )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    _lowerCamelCase       :		Tuple		=type
                    self.model_tester.create_and_check_model(*lowercase_ )






      def        lowerCamelCase       (					self						:     Tuple )					->						List[str]:
             """simple docstring"""




             _lowerCamelCase	,     _lowerCamelCase       :		List[str]		=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase       :		str		=3
             _lowerCamelCase       :		str		=input_dict['input_ids']
             _lowerCamelCase       :		int		=input_ids.ne(1 ).to(lowercase_ )
             _lowerCamelCase       :		Optional[Any]		=ids_tensor([self.model_tester.batch_size]			,   self.model_tester.type_sequence_label_size )
             _lowerCamelCase       :		Union[str, Any]		=LlamaForSequenceClassification(lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		Dict		=model(lowercase_			,   attention_mask=lowercase_			,   labels=lowercase_ )
             self.assertEqual(result.logits.shape			,   (self.model_tester.batch_size, self.model_tester.num_labels) )






      def        lowerCamelCase       (					self						:     Tuple )					->						Optional[Any]:
             """simple docstring"""




             _lowerCamelCase	,     _lowerCamelCase       :		Optional[int]		=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase       :		Optional[Any]		=3
             _lowerCamelCase       :		List[Any]		='single_label_classification'
             _lowerCamelCase       :		List[str]		=input_dict['input_ids']
             _lowerCamelCase       :		Any		=input_ids.ne(1 ).to(lowercase_ )
             _lowerCamelCase       :		List[str]		=ids_tensor([self.model_tester.batch_size]			,   self.model_tester.type_sequence_label_size )
             _lowerCamelCase       :		str		=LlamaForSequenceClassification(lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		Optional[int]		=model(lowercase_			,   attention_mask=lowercase_			,   labels=lowercase_ )
             self.assertEqual(result.logits.shape			,   (self.model_tester.batch_size, self.model_tester.num_labels) )






      def        lowerCamelCase       (					self						:     Dict )					->						int:
             """simple docstring"""




             _lowerCamelCase	,     _lowerCamelCase       :		List[str]		=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase       :		int		=3
             _lowerCamelCase       :		Optional[Any]		='multi_label_classification'
             _lowerCamelCase       :		str		=input_dict['input_ids']
             _lowerCamelCase       :		Tuple		=input_ids.ne(1 ).to(lowercase_ )
             _lowerCamelCase       :		Tuple		=ids_tensor(
                 [self.model_tester.batch_size, config.num_labels]			,   self.model_tester.type_sequence_label_size ).to(torch.float )
             _lowerCamelCase       :		Optional[Any]		=LlamaForSequenceClassification(lowercase_ )
             model.to(lowercase_ )
             model.eval()
             _lowerCamelCase       :		Optional[Any]		=model(lowercase_			,   attention_mask=lowercase_			,   labels=lowercase_ )
             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						:     int )					->						str:
             """simple docstring"""




             pass






      @parameterized.expand([('linear',), ('dynamic',)] )
      def        lowerCamelCase       (					self						:     Optional[int]			,   lowercase_						:     List[Any] )					->						int:
             """simple docstring"""




             _lowerCamelCase	,     _lowerCamelCase       :		Optional[int]		=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase       :		Union[str, Any]		=ids_tensor([1, 10]			,   config.vocab_size )
             _lowerCamelCase       :		List[str]		=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       :		Optional[int]		=LlamaModel(lowercase_ )
             original_model.to(lowercase_ )
             original_model.eval()
             _lowerCamelCase       :		List[Any]		=original_model(lowercase_ ).last_hidden_state
             _lowerCamelCase       :		Dict		=original_model(lowercase_ ).last_hidden_state

             set_seed(42 )  # Fixed seed at init time so the two models get the same random weights
             _lowerCamelCase       :		Dict		={'type': scaling_type, 'factor': 10.0}
             _lowerCamelCase       :		int		=LlamaModel(lowercase_ )
             scaled_model.to(lowercase_ )
             scaled_model.eval()
             _lowerCamelCase       :		Optional[int]		=scaled_model(lowercase_ ).last_hidden_state
             _lowerCamelCase       :		Dict		=scaled_model(lowercase_ ).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(lowercase_			,   lowercase_			,   atol=1E-5 ) )
             else:
                    self.assertFalse(torch.allclose(lowercase_			,   lowercase_			,   atol=1E-5 ) )

             # The output should be different for long inputs
             self.assertFalse(torch.allclose(lowercase_			,   lowercase_			,   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						:     Tuple )					->						Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=[1, 306, 4658, 278, 6593, 310, 2834, 338]
             _lowerCamelCase       :		Optional[Any]		=LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'			,   device_map='auto' )
             _lowerCamelCase       :		int		=model(torch.tensor([input_ids] ) )
             # Expected mean on dim = -1
             _lowerCamelCase       :		int		=torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] )
             torch.testing.assert_close(out.mean(-1 )			,   lowercase_			,   atol=1E-2			,   rtol=1E-2 )
             # slicing logits[0, 0, 0:30]
             # fmt: off
             _lowerCamelCase       :		Dict		=torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] )
             # fmt: on
             torch.testing.assert_close(out[0, 0, :30]			,   lowercase_			,   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						:     int )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		Tuple		=[1, 306, 4658, 278, 6593, 310, 2834, 338]
             _lowerCamelCase       :		Optional[Any]		=LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'			,   device_map='auto' )
             _lowerCamelCase       :		List[Any]		=model(torch.tensor(lowercase_ ) )
             # Expected mean on dim = -1
             _lowerCamelCase       :		str		=torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] )
             torch.testing.assert_close(out.mean(-1 )			,   lowercase_			,   atol=1E-2			,   rtol=1E-2 )
             # slicing logits[0, 0, 0:30]
             # fmt: off
             _lowerCamelCase       :		List[str]		=torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] )
             # fmt: on
             torch.testing.assert_close(out[0, 0, :30]			,   lowercase_			,   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						:     List[Any] )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=[1, 306, 4658, 278, 6593, 310, 2834, 338]
             _lowerCamelCase       :		str		=LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'			,   device_map='auto' )
             _lowerCamelCase       :		int		=model(torch.tensor(lowercase_ ) )
             # Expected mean on dim = -1
             _lowerCamelCase       :		str		=torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] )
             torch.testing.assert_close(out.mean(-1 )			,   lowercase_			,   atol=1E-2			,   rtol=1E-2 )
             # slicing logits[0, 0, 0:30]
             # fmt: off
             _lowerCamelCase       :		Union[str, Any]		=torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] )
             # fmt: on
             torch.testing.assert_close(out.mean(-1 )			,   lowercase_			,   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						:     int )					->						List[Any]:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=[1, 306, 4658, 278, 6593, 310, 2834, 338]
             _lowerCamelCase       :		Any		=LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'			,   device_map='auto' )
             _lowerCamelCase       :		Optional[Any]		=model(torch.tensor(lowercase_ ) )

             _lowerCamelCase       :		Optional[int]		=torch.tensor(
                 [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]]			,   dtype=torch.floataa )
             torch.testing.assert_close(out.mean(-1 )			,   lowercase_			,   atol=1E-2			,   rtol=1E-2 )
             # fmt: off
             _lowerCamelCase       :		int		=torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] )
             # fmt: on
             torch.testing.assert_close(out[0, 0, :30]			,   lowercase_			,   atol=1E-5			,   rtol=1E-5 )






      @unittest.skip('Model is curently gated' )
      @slow
      def        lowerCamelCase       (					self						:     str )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		Tuple		='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       :		Union[str, Any]		='Simply put, the theory of relativity states that '
             _lowerCamelCase       :		int		=LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' )
             _lowerCamelCase       :		str		=tokenizer.encode(lowercase_			,   return_tensors='pt' )
             _lowerCamelCase       :		List[Any]		=LlamaForCausalLM.from_pretrained(
                 'meta-llama/Llama-2-13b-chat-hf'			,   device_map='sequential'			,   use_safetensors=lowercase_ )

             # greedy generation outputs
             _lowerCamelCase       :		str		=model.generate(lowercase_			,   max_new_tokens=64			,   top_p=lowercase_			,   temperature=1			,   do_sample=lowercase_ )
             _lowerCamelCase       :		Tuple		=tokenizer.decode(generated_ids[0]			,   skip_special_tokens=lowercase_ )
             self.assertEqual(lowercase_			,   lowercase_ )


