


'''simple docstring'''
import argparse

import torch

from transformers import (
    EncodecConfig,
    EncodecFeatureExtractor,
    EncodecModel,
    logging,
)


# checkpoints downloaded from:
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th
# https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th


logging.set_verbosity_info()
UpperCAmelCase_ :     int								=      logging.get_logger('transformers.models.encodec')

UpperCAmelCase_ :     List[Any]								=      {
    'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited',
    'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size',
    'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed',
    'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg',
}
UpperCAmelCase_ :     str								=      {
    'encoder.model.0.conv.conv': 'encoder.layers.0.conv',
    'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv',
    'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv',
    'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv',
    'encoder.model.3.conv.conv': 'encoder.layers.3.conv',
    'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv',
    'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv',
    'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv',
    'encoder.model.6.conv.conv': 'encoder.layers.6.conv',
    'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv',
    'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv',
    'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv',
    'encoder.model.9.conv.conv': 'encoder.layers.9.conv',
    'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv',
    'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv',
    'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv',
    'encoder.model.12.conv.conv': 'encoder.layers.12.conv',
    'encoder.model.13.lstm': 'encoder.layers.13.lstm',
    'encoder.model.15.conv.conv': 'encoder.layers.15.conv',
}
UpperCAmelCase_ :     List[str]								=      {
    'encoder.model.0.conv.norm': 'encoder.layers.0.norm',
    'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm',
    'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm',
    'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm',
    'encoder.model.3.conv.norm': 'encoder.layers.3.norm',
    'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm',
    'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm',
    'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm',
    'encoder.model.6.conv.norm': 'encoder.layers.6.norm',
    'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm',
    'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm',
    'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm',
    'encoder.model.9.conv.norm': 'encoder.layers.9.norm',
    'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm',
    'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm',
    'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm',
    'encoder.model.12.conv.norm': 'encoder.layers.12.norm',
    'encoder.model.15.conv.norm': 'encoder.layers.15.norm',
}
UpperCAmelCase_ :     List[Any]								=      {
    'decoder.model.0.conv.conv': 'decoder.layers.0.conv',
    'decoder.model.1.lstm': 'decoder.layers.1.lstm',
    'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv',
    'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv',
    'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv',
    'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv',
    'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv',
    'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv',
    'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv',
    'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv',
    'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv',
    'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv',
    'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv',
    'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv',
    'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv',
    'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv',
    'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv',
    'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv',
    'decoder.model.15.conv.conv': 'decoder.layers.15.conv',
}
UpperCAmelCase_ :     List[str]								=      {
    'decoder.model.0.conv.norm': 'decoder.layers.0.norm',
    'decoder.model.3.convtr.norm': 'decoder.layers.3.norm',
    'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm',
    'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm',
    'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm',
    'decoder.model.6.convtr.norm': 'decoder.layers.6.norm',
    'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm',
    'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm',
    'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm',
    'decoder.model.9.convtr.norm': 'decoder.layers.9.norm',
    'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm',
    'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm',
    'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm',
    'decoder.model.12.convtr.norm': 'decoder.layers.12.norm',
    'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm',
    'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm',
    'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm',
    'decoder.model.15.conv.norm': 'decoder.layers.15.norm',
}
UpperCAmelCase_ :     List[Any]								=      {
    **MAPPING_QUANTIZER,
    **MAPPING_ENCODER,
    **MAPPING_DECODER,
}
UpperCAmelCase_ :     List[str]								=      {
    **MAPPING_QUANTIZER,
    **MAPPING_ENCODER,
    **MAPPING_ENCODER_48K,
    **MAPPING_DECODER,
    **MAPPING_DECODER_48K,
}
UpperCAmelCase_ :     Optional[int]								=      []
UpperCAmelCase_ :     Dict								=      []


def 			_lowercase       (				UpperCamelCase__       :					Any,				UpperCamelCase__       :					str,				UpperCamelCase__       :					List[Any],				UpperCamelCase__       :					Any,				UpperCamelCase__       :					List[Any]			):
 for attribute in key.split('.'			):
  __A  :		str       =			getattr(UpperCamelCase__,				UpperCamelCase__			)

 if weight_type is not None:
  __A  :		Tuple       =			getattr(UpperCamelCase__,				UpperCamelCase__			).shape
 else:
  __A  :		str       =			hf_pointer.shape

 if hf_shape != value.shape:
  raise ValueError(
      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":
  __A  :		int       =			value
 elif weight_type == "weight_g":
  __A  :		List[str]       =			value
 elif weight_type == "weight_v":
  __A  :		Optional[int]       =			value
 elif weight_type == "bias":
  __A  :		Optional[Any]       =			value
 elif weight_type == "running_mean":
  __A  :		int       =			value
 elif weight_type == "running_var":
  __A  :		Any       =			value
 elif weight_type == "num_batches_tracked":
  __A  :		List[Any]       =			value
 elif weight_type == "weight_ih_l0":
  __A  :		Any       =			value
 elif weight_type == "weight_hh_l0":
  __A  :		Union[str, Any]       =			value
 elif weight_type == "bias_ih_l0":
  __A  :		int       =			value
 elif weight_type == "bias_hh_l0":
  __A  :		List[Any]       =			value
 elif weight_type == "weight_ih_l1":
  __A  :		Union[str, Any]       =			value
 elif weight_type == "weight_hh_l1":
  __A  :		List[Any]       =			value
 elif weight_type == "bias_ih_l1":
  __A  :		Tuple       =			value
 elif weight_type == "bias_hh_l1":
  __A  :		int       =			value
 else:
  __A  :		Union[str, Any]       =			value

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


def 			_lowercase       (				UpperCamelCase__       :					str,				UpperCamelCase__       :					Any			):
 for key in ignore_keys:
  if key.endswith('.*'			):
   if name.startswith(key[:-1]			):
    return True
  elif ".*." in key:
   __A     ,__A  :		Any       =			key.split('.*.'			)
   if prefix in name and suffix in name:
    return True
  elif key in name:
   return True
 return False


def 			_lowercase       (				UpperCamelCase__       :					Union[str, Any],				UpperCamelCase__       :					Union[str, Any],				UpperCamelCase__       :					List[Any]			):
 __A  :		Dict       =			[]

 if model_name == "encodec_24khz" or "encodec_32khz":
  __A  :		Optional[Any]       =			MAPPING_24K
 elif model_name == "encodec_48khz":
  __A  :		Union[str, Any]       =			MAPPING_48K
 else:
  raise ValueError(f"""Unsupported model: {model_name}"""			)

 for name, value in orig_dict.items():
  if should_ignore(UpperCamelCase__,				UpperCamelCase__			):
   logger.info(f"""{name} was ignored"""			)
   continue

  __A  :		int       =			False
  for key, mapped_key in MAPPING.items():
   if "*" in key:
    __A     ,__A  :		str       =			key.split('.*.'			)
    if prefix in name and suffix in name:
     __A  :		Dict       =			suffix

   if key in name:
    # HACK otherwise .embed gets initialized with .embed_avg too
    if key.endswith('embed'			) and name.endswith('embed_avg'			):
     continue

    __A  :		List[Any]       =			True
    if "*" in mapped_key:
     __A  :		List[str]       =			name.split(UpperCamelCase__			)[0].split('.'			)[-2]
     __A  :		Tuple       =			mapped_key.replace('*',				UpperCamelCase__			)
    if "weight_g" in name:
     __A  :		Any       =			'weight_g'
    elif "weight_v" in name:
     __A  :		Optional[int]       =			'weight_v'
    elif "weight_ih_l0" in name:
     __A  :		Optional[Any]       =			'weight_ih_l0'
    elif "weight_hh_l0" in name:
     __A  :		List[Any]       =			'weight_hh_l0'
    elif "bias_ih_l0" in name:
     __A  :		Optional[Any]       =			'bias_ih_l0'
    elif "bias_hh_l0" in name:
     __A  :		Optional[int]       =			'bias_hh_l0'
    elif "weight_ih_l1" in name:
     __A  :		Tuple       =			'weight_ih_l1'
    elif "weight_hh_l1" in name:
     __A  :		Optional[Any]       =			'weight_hh_l1'
    elif "bias_ih_l1" in name:
     __A  :		Tuple       =			'bias_ih_l1'
    elif "bias_hh_l1" in name:
     __A  :		Dict       =			'bias_hh_l1'
    elif "bias" in name:
     __A  :		Optional[Any]       =			'bias'
    elif "weight" in name:
     __A  :		Tuple       =			'weight'
    elif "running_mean" in name:
     __A  :		List[str]       =			'running_mean'
    elif "running_var" in name:
     __A  :		Any       =			'running_var'
    elif "num_batches_tracked" in name:
     __A  :		Dict       =			'num_batches_tracked'
    else:
     __A  :		Union[str, Any]       =			None
    set_recursively(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)
   continue
  if not is_used:
   unused_weights.append(UpperCamelCase__			)

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


@torch.no_grad()
def 			_lowercase       (				UpperCamelCase__       :					Union[str, Any],				UpperCamelCase__       :					str,				UpperCamelCase__       :					Union[str, Any],				UpperCamelCase__       :					str=None,				UpperCamelCase__       :					str=None,				):
 if config_path is not None:
  __A  :		List[Any]       =			EncodecConfig.from_pretrained(UpperCamelCase__			)
 else:
  __A  :		Any       =			EncodecConfig()

 if model_name == "encodec_24khz":
  pass  # config is already correct
 elif model_name == "encodec_32khz":
  __A  :		Tuple       =			[8, 5, 4, 4]
  __A  :		int       =			[2.2]
  __A  :		str       =			64
  __A  :		List[Any]       =			32000
  __A  :		Dict       =			2048
  __A  :		int       =			False
  __A  :		str       =			False
  __A  :		str       =			False
 elif model_name == "encodec_48khz":
  __A  :		List[str]       =			[8, 5, 4, 2]
  __A  :		Union[str, Any]       =			[3.0, 6.0, 12.0, 24.0]
  __A  :		Optional[int]       =			48000
  __A  :		Tuple       =			2
  __A  :		Tuple       =			False
  __A  :		List[Any]       =			'time_group_norm'
  __A  :		Tuple       =			True
  __A  :		Optional[Any]       =			1.0
  __A  :		str       =			0.01
 else:
  raise ValueError(f"""Unknown model name: {model_name}"""			)

 __A  :		Tuple       =			EncodecModel(UpperCamelCase__			)

 __A  :		int       =			EncodecFeatureExtractor(
     feature_size=config.audio_channels,				sampling_rate=config.sampling_rate,				chunk_length_s=config.chunk_length_s,				overlap=config.overlap,				)
 feature_extractor.save_pretrained(UpperCamelCase__			)

 __A  :		Union[str, Any]       =			torch.load(UpperCamelCase__			)
 if "best_state" in original_checkpoint:
  # we might have a training state saved, in which case discard the yaml results and just retain the weights
  __A  :		str       =			original_checkpoint['best_state']
 recursively_load_weights(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)
 model.save_pretrained(UpperCamelCase__			)

 if repo_id:
  print('Pushing to the hub...'			)
  feature_extractor.push_to_hub(UpperCamelCase__			)
  model.push_to_hub(UpperCamelCase__			)


if __name__ == "__main__":
 UpperCAmelCase_ :     Dict								=      argparse.ArgumentParser()
 parser.add_argument(
     '--model',
     default='encodec_24khz',
     type=str,
     help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.',
 )
 parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint')
 parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
 parser.add_argument(
     '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.'
 )
 parser.add_argument(
     '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.'
 )

 UpperCAmelCase_ :     Tuple								=      parser.parse_args()
 convert_checkpoint(
     args.model,
     args.checkpoint_path,
     args.pytorch_dump_folder_path,
     args.config_path,
     args.push_to_hub,
 )










'''simple docstring'''
import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase=13      ,      __lowercase=7      ,      __lowercase=True      ,      __lowercase=True      ,      __lowercase=False      ,      __lowercase=True      ,      __lowercase=99      ,      __lowercase=32      ,      __lowercase=5      ,      __lowercase=4      ,      __lowercase=37      ,      __lowercase="gelu"      ,      __lowercase=0.1      ,      __lowercase=0.1      ,      __lowercase=512      ,      __lowercase=16      ,      __lowercase=2      ,      __lowercase=0.0_2      ,      __lowercase=3      ,      __lowercase=4      ,      __lowercase=None      ,      ):

  """simple docstring"""







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


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			ids_tensor([self.batch_size, self.seq_length]      ,      self.vocab_size						)

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

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

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

  __A  :		List[Any]       =			self.get_config()

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


 def  snake_case__   (      self						):

  """simple docstring"""







  return OpenLlamaConfig(
      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      ,      use_stable_embedding=__lowercase      ,      )


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		List[str]       =			OpenLlamaModel(config=__lowercase						)
  model.to(__lowercase						)
  model.eval()
  __A  :		Any       =			model(__lowercase      ,      attention_mask=__lowercase						)
  __A  :		Dict       =			model(__lowercase						)
  self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.seq_length, self.hidden_size)						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      ):

  """simple docstring"""







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


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      ):

  """simple docstring"""







  __A  :		Dict       =			OpenLlamaForCausalLM(config=__lowercase						)
  model.to(__lowercase						)
  model.eval()
  __A  :		Optional[Any]       =			model(__lowercase      ,      attention_mask=__lowercase      ,      labels=__lowercase						)
  self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.vocab_size)						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      ):

  """simple docstring"""







  __A  :		List[Any]       =			True
  __A  :		Optional[int]       =			True
  __A  :		Dict       =			OpenLlamaForCausalLM(config=__lowercase						)
  model.to(__lowercase						)
  model.eval()

  # first forward pass
  __A  :		List[str]       =			model(
      __lowercase      ,      attention_mask=__lowercase      ,      encoder_hidden_states=__lowercase      ,      encoder_attention_mask=__lowercase      ,      use_cache=__lowercase      ,      )
  __A  :		Optional[Any]       =			outputs.past_key_values

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

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

  __A  :		Tuple       =			model(
      __lowercase      ,      attention_mask=__lowercase      ,      encoder_hidden_states=__lowercase      ,      encoder_attention_mask=__lowercase      ,      output_hidden_states=__lowercase      ,      )['hidden_states'][0]
  __A  :		Any       =			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
  __A  :		Any       =			ids_tensor((1,)      ,      output_from_past.shape[-1]						).item()
  __A  :		Union[str, Any]       =			output_from_no_past[:, -3:, random_slice_idx].detach()
  __A  :		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  snake_case__   (      self						):

  """simple docstring"""







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


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




 '''simple docstring'''
 __lowercase				:		List[str]    							=						(
     (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
 )
 __lowercase				:		List[Any]    							=						(OpenLlamaForCausalLM,) if is_torch_available() else ()
 __lowercase				:		Optional[int]    							=						(
     {
         '''feature-extraction''': OpenLlamaModel,
         '''text-classification''': OpenLlamaForSequenceClassification,
         '''text-generation''': OpenLlamaForCausalLM,
         '''zero-shot''': OpenLlamaForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowercase				:		Union[str, Any]    							=						False
 __lowercase				:		Union[str, Any]    							=						False


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			OpenLlamaModelTester(self						)
  __A  :		List[str]       =			ConfigTester(self      ,      config_class=__lowercase      ,      hidden_size=37						)


 def  snake_case__   (      self						):

  """simple docstring"""







  self.config_tester.run_common_tests()


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*__lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			self.model_tester.prepare_config_and_inputs()
  for type in ["absolute", "relative_key", "relative_key_query"]:
   __A  :		List[str]       =			type
   self.model_tester.create_and_check_model(*__lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A     ,__A  :		Optional[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()
  __A  :		Union[str, Any]       =			3
  __A  :		int       =			input_dict['input_ids']
  __A  :		int       =			input_ids.ne(1						).to(__lowercase						)
  __A  :		Optional[int]       =			ids_tensor([self.model_tester.batch_size]      ,      self.model_tester.type_sequence_label_size						)
  __A  :		Optional[Any]       =			OpenLlamaForSequenceClassification(__lowercase						)
  model.to(__lowercase						)
  model.eval()
  __A  :		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  snake_case__   (      self						):

  """simple docstring"""







  __A     ,__A  :		str       =			self.model_tester.prepare_config_and_inputs_for_common()
  __A  :		Any       =			3
  __A  :		List[str]       =			'single_label_classification'
  __A  :		Dict       =			input_dict['input_ids']
  __A  :		Dict       =			input_ids.ne(1						).to(__lowercase						)
  __A  :		List[str]       =			ids_tensor([self.model_tester.batch_size]      ,      self.model_tester.type_sequence_label_size						)
  __A  :		Union[str, Any]       =			OpenLlamaForSequenceClassification(__lowercase						)
  model.to(__lowercase						)
  model.eval()
  __A  :		Dict       =			model(__lowercase      ,      attention_mask=__lowercase      ,      labels=__lowercase						)
  self.assertEqual(result.logits.shape      ,      (self.model_tester.batch_size, self.model_tester.num_labels)						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A     ,__A  :		Optional[int]       =			self.model_tester.prepare_config_and_inputs_for_common()
  __A  :		str       =			3
  __A  :		int       =			'multi_label_classification'
  __A  :		Union[str, Any]       =			input_dict['input_ids']
  __A  :		str       =			input_ids.ne(1						).to(__lowercase						)
  __A  :		Union[str, Any]       =			ids_tensor(
      [self.model_tester.batch_size, config.num_labels]      ,      self.model_tester.type_sequence_label_size						).to(torch.float						)
  __A  :		int       =			OpenLlamaForSequenceClassification(__lowercase						)
  model.to(__lowercase						)
  model.eval()
  __A  :		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('Open-Llama buffers include complex numbers, which breaks this test'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass







 @parameterized.expand([('linear',), ('dynamic',)]						)
 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







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

  set_seed(42						)  # Fixed seed at init time so the two models get the same random weights
  __A  :		List[Any]       =			{'type': scaling_type, 'factor': 1_0.0}
  __A  :		str       =			OpenLlamaModel(__lowercase						)
  scaled_model.to(__lowercase						)
  scaled_model.eval()
  __A  :		Dict       =			scaled_model(__lowercase						).last_hidden_state
  __A  :		List[str]       =			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						)						)






