






"""simple docstring"""







import gc
import unittest

from transformers import CTRLConfig, is_torch_available
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 (
     CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
     CTRLForSequenceClassification,
     CTRLLMHeadModel,
     CTRLModel,
 )





class   UpperCamelCase_ :



  def __init__(      self ,		snake_case__ ,		snake_case__=14 ,		snake_case__=7 ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=99 ,		snake_case__=32 ,		snake_case__=5 ,		snake_case__=4 ,		snake_case__=37 ,		snake_case__="gelu" ,		snake_case__=0.1 ,		snake_case__=0.1 ,		snake_case__=5_12 ,		snake_case__=16 ,		snake_case__=2 ,		snake_case__=0.02 ,		snake_case__=3 ,		snake_case__=4 ,		snake_case__=None ,		)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			parent
         UpperCAmelCase	    =			batch_size
         UpperCAmelCase	    =			seq_length
         UpperCAmelCase	    =			is_training
         UpperCAmelCase	    =			use_token_type_ids
         UpperCAmelCase	    =			use_input_mask
         UpperCAmelCase	    =			use_labels
         UpperCAmelCase	    =			use_mc_token_ids
         UpperCAmelCase	    =			vocab_size
         UpperCAmelCase	    =			hidden_size
         UpperCAmelCase	    =			num_hidden_layers
         UpperCAmelCase	    =			num_attention_heads
         UpperCAmelCase	    =			intermediate_size
         UpperCAmelCase	    =			hidden_act
         UpperCAmelCase	    =			hidden_dropout_prob
         UpperCAmelCase	    =			attention_probs_dropout_prob
         UpperCAmelCase	    =			max_position_embeddings
         UpperCAmelCase	    =			type_vocab_size
         UpperCAmelCase	    =			type_sequence_label_size
         UpperCAmelCase	    =			initializer_range
         UpperCAmelCase	    =			num_labels
         UpperCAmelCase	    =			num_choices
         UpperCAmelCase	    =			scope
         UpperCAmelCase	    =			self.vocab_size - 1



  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase	    =			ids_tensor([self.batch_size, self.seq_length] ,		self.vocab_size				)

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

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

         UpperCAmelCase	    =			None
         if self.use_mc_token_ids:
                UpperCAmelCase	    =			ids_tensor([self.batch_size, self.num_choices] ,		self.seq_length				)

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

         UpperCAmelCase	    =			self.get_config()

         UpperCAmelCase	    =			ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,		2				)

         return (
             config,
             input_ids,
             input_mask,
             head_mask,
             token_type_ids,
             mc_token_ids,
             sequence_labels,
             token_labels,
             choice_labels,
         )



  def 		UpperCamelCase_				(      self				)			->			str:



         """simple docstring"""





         return CTRLConfig(
             vocab_size=self.vocab_size ,		n_embd=self.hidden_size ,		n_layer=self.num_hidden_layers ,		n_head=self.num_attention_heads ,		n_positions=self.max_position_embeddings ,		pad_token_id=self.pad_token_id ,		)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase	    =			CTRLModel(config=snake_case__				)
         model.to(snake_case__				)
         model.eval()

         model(snake_case__ ,		token_type_ids=snake_case__ ,		head_mask=snake_case__				)
         model(snake_case__ ,		token_type_ids=snake_case__				)
         UpperCAmelCase	    =			model(snake_case__				)
         self.parent.assertEqual(result.last_hidden_state.shape ,		(self.batch_size, self.seq_length, self.hidden_size)				)
         self.parent.assertEqual(len(result.past_key_values				) ,		config.n_layer				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase	    =			CTRLLMHeadModel(snake_case__				)
         model.to(snake_case__				)
         model.eval()

         UpperCAmelCase	    =			model(snake_case__ ,		token_type_ids=snake_case__ ,		labels=snake_case__				)
         self.parent.assertEqual(result.loss.shape ,		()				)
         self.parent.assertEqual(result.logits.shape ,		(self.batch_size, self.seq_length, self.vocab_size)				)



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



         """simple docstring"""





         UpperCAmelCase	    =			self.prepare_config_and_inputs()

         (
             (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       
         )	    =			config_and_inputs

         UpperCAmelCase	    =			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

         return config, inputs_dict



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		*snake_case__				)			->			str:



         """simple docstring"""





         UpperCAmelCase	    =			self.num_labels
         UpperCAmelCase	    =			CTRLForSequenceClassification(snake_case__				)
         model.to(snake_case__				)
         model.eval()
         UpperCAmelCase	    =			ids_tensor([self.batch_size] ,		self.type_sequence_label_size				)
         UpperCAmelCase	    =			model(snake_case__ ,		token_type_ids=snake_case__ ,		labels=snake_case__				)
         self.parent.assertEqual(result.logits.shape ,		(self.batch_size, self.num_labels)				)





@require_torch
class   UpperCamelCase_ (       a_   ,					a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					Any				=	(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
  _A       :					Tuple				=	(CTRLLMHeadModel,) if is_torch_available() else ()
  _A       :					int				=	(
      {
          'feature-extraction': CTRLModel,
          'text-classification': CTRLForSequenceClassification,
          'text-generation': CTRLLMHeadModel,
          'zero-shot': CTRLForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  _A       :					List[Any]				=	True
  _A       :					List[Any]				=	False
  _A       :					str				=	False



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__				)			->			List[Any]:



         """simple docstring"""





         if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
                # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
                # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
                # config could not be created.
                return True

         return False



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         UpperCAmelCase	    =			CTRLModelTester(self				)
         UpperCAmelCase	    =			ConfigTester(self ,		config_class=snake_case__ ,		n_embd=37				)



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



         """simple docstring"""





         super().tearDown()
         # clean-up as much as possible GPU memory occupied by PyTorch
         gc.collect()
         torch.cuda.empty_cache()



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



         """simple docstring"""





         self.config_tester.run_common_tests()



  def 		UpperCamelCase_				(      self				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_model(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_lm_head_model(*snake_case__				)



  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""				)
  def 		UpperCamelCase_				(      self				)			->			Optional[int]:



         """simple docstring"""





         pass



  @slow
  def 		UpperCamelCase_				(      self				)			->			Union[str, Any]:



         """simple docstring"""





         for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase	    =			CTRLModel.from_pretrained(snake_case__				)
                self.assertIsNotNone(snake_case__				)



  @unittest.skip("""The model doesn't support left padding"""				)  # and it's not used enough to be worth fixing :)
  def 		UpperCamelCase_				(      self				)			->			List[Any]:



         """simple docstring"""





         pass





@require_torch
class   UpperCamelCase_ (       unittest.TestCase  ):



  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         super().tearDown()
         # clean-up as much as possible GPU memory occupied by PyTorch
         gc.collect()
         torch.cuda.empty_cache()



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



         """simple docstring"""





         UpperCAmelCase	    =			CTRLLMHeadModel.from_pretrained("""ctrl"""				)
         model.to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor(
             [[1_18_59, 0, 16_11, 8]] ,		dtype=torch.long ,		device=snake_case__				)  # Legal the president is
         UpperCAmelCase	    =			[
             1_18_59,
             0,
             16_11,
             8,
             5,
             1_50,
             2_64_49,
             2,
             19,
             3_48,
             4_69,
             3,
             25_95,
             48,
             2_07_40,
             24_65_33,
             24_65_33,
             19,
             30,
             5,
         ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

         UpperCAmelCase	    =			model.generate(snake_case__ ,		do_sample=snake_case__				)
         self.assertListEqual(output_ids[0].tolist() ,		snake_case__				)








"""simple docstring"""







import math
from typing import Optional

import numpy as np

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase_	:    List[Any]            =      logging.get_logger(__name__)

lowerCAmelCase_	:    Optional[Any]            =      {
    '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''',
    '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''',
}





class   UpperCamelCase_ (       a_  ):
  _A       :					Dict				=	'encodec'



  def __init__(      self ,		snake_case__=[1.5, 3.0, 6.0, 12.0, 24.0] ,		snake_case__=2_40_00 ,		snake_case__=1 ,		snake_case__=False ,		snake_case__=None ,		snake_case__=None ,		snake_case__=1_28 ,		snake_case__=32 ,		snake_case__=1 ,		snake_case__=[8, 5, 4, 2] ,		snake_case__="weight_norm" ,		snake_case__=7 ,		snake_case__=7 ,		snake_case__=3 ,		snake_case__=2 ,		snake_case__=True ,		snake_case__="reflect" ,		snake_case__=2 ,		snake_case__=2 ,		snake_case__=1.0 ,		snake_case__=10_24 ,		snake_case__=None ,		snake_case__=True ,		**snake_case__ ,		)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			target_bandwidths
         UpperCAmelCase	    =			sampling_rate
         UpperCAmelCase	    =			audio_channels
         UpperCAmelCase	    =			normalize
         UpperCAmelCase	    =			chunk_length_s
         UpperCAmelCase	    =			overlap
         UpperCAmelCase	    =			hidden_size
         UpperCAmelCase	    =			num_filters
         UpperCAmelCase	    =			num_residual_layers
         UpperCAmelCase	    =			upsampling_ratios
         UpperCAmelCase	    =			norm_type
         UpperCAmelCase	    =			kernel_size
         UpperCAmelCase	    =			last_kernel_size
         UpperCAmelCase	    =			residual_kernel_size
         UpperCAmelCase	    =			dilation_growth_rate
         UpperCAmelCase	    =			use_causal_conv
         UpperCAmelCase	    =			pad_mode
         UpperCAmelCase	    =			compress
         UpperCAmelCase	    =			num_lstm_layers
         UpperCAmelCase	    =			trim_right_ratio
         UpperCAmelCase	    =			codebook_size
         UpperCAmelCase	    =			codebook_dim if codebook_dim is not None else hidden_size
         UpperCAmelCase	    =			use_conv_shortcut

         if self.norm_type not in ["weight_norm", "time_group_norm"]:
                raise ValueError(
                    f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}'''				)

         super().__init__(**snake_case__				)



  @property
  def 		UpperCamelCase_				(      self				)			->			Optional[int]:



         """simple docstring"""





         if self.chunk_length_s is None:
                return None
         else:
                return int(self.chunk_length_s * self.sampling_rate				)



  @property
  def 		UpperCamelCase_				(      self				)			->			Optional[int]:



         """simple docstring"""





         if self.chunk_length_s is None or self.overlap is None:
                return None
         else:
                return max(1 ,		int((1.0 - self.overlap) * self.chunk_length				)				)



  @property
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         UpperCAmelCase	    =			np.prod(self.upsampling_ratios				)
         return math.ceil(self.sampling_rate / hop_length				)



  @property
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10)				)
