




'''simple docstring'''







import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
   import torch

   from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin


class 			_a  :
       def __init__(	self						:	List[str]   ,				lowercase						:	Optional[int]   ,				lowercase						:	List[str]=None   ,				lowercase						:	Tuple=None   ,				lowercase						:	int=None   ,				lowercase						:	List[str]="resnet50"   ,				lowercase						:	Optional[Any]=3   ,				lowercase						:	str=32   ,				lowercase						:	List[Any]=3   ,				lowercase						:	int=True   ,				lowercase						:	Any=True   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		parent
           UpperCAmelCase			       =		out_indices if out_indices is not None else [4]
           UpperCAmelCase			       =		stage_names
           UpperCAmelCase			       =		out_features
           UpperCAmelCase			       =		backbone
           UpperCAmelCase			       =		batch_size
           UpperCAmelCase			       =		image_size
           UpperCAmelCase			       =		num_channels
           UpperCAmelCase			       =		use_pretrained_backbone
           UpperCAmelCase			       =		is_training
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           UpperCAmelCase			       =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)
           UpperCAmelCase			       =		self.get_config()

           return config, pixel_values
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           return TimmBackboneConfig(
               image_size=self.image_size   ,				num_channels=self.num_channels   ,				out_features=self.out_features   ,				out_indices=self.out_indices   ,				stage_names=self.stage_names   ,				use_pretrained_backbone=self.use_pretrained_backbone   ,				backbone=self.backbone   ,				)
       def     A      (	self						:	Tuple   ,				lowercase						:	List[Any]   ,				lowercase						:	Union[str, Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		TimmBackbone(config=lowercase				)
           model.to(lowercase				)
           model.eval()
           with torch.no_grad():
               UpperCAmelCase			       =		model(lowercase				)
           self.parent.assertEqual(
               result.feature_map[-1].shape   ,				(self.batch_size, model.channels[-1], 14, 14)   ,				)







       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.prepare_config_and_inputs()
           UpperCAmelCase       ,     UpperCAmelCase			       =		config_and_inputs
           UpperCAmelCase			       =		{'''pixel_values''': pixel_values}
           return config, inputs_dict






@require_torch
@require_timm
class 			_a  (	__a							,							__a							,							__a							,							unittest.TestCase ):
       __a				:     Optional[int]   				=					(TimmBackbone,) if is_torch_available() else ()
       __a				:     Dict   				=					{"""feature-extraction""": TimmBackbone} if is_torch_available() else {}
       __a				:     Optional[Any]   				=					False
       __a				:     List[str]   				=					False
       __a				:     int   				=					False
       __a				:     Optional[Any]   				=					False
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           UpperCAmelCase			       =		TimmBackboneModelTester(self				)
           UpperCAmelCase			       =		ConfigTester(self   ,				config_class=lowercase   ,				has_text_modality=lowercase				)
       def     A      (	self						:	str				):



           '''simple docstring'''

           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''resnet18'''
           UpperCAmelCase			       =		'''microsoft/resnet-18'''

           UpperCAmelCase			       =		AutoBackbone.from_pretrained(lowercase   ,				use_timm_backbone=lowercase				)
           UpperCAmelCase			       =		AutoBackbone.from_pretrained(lowercase				)

           self.assertEqual(len(timm_model.out_features				)   ,				len(transformers_model.out_features				)				)
           self.assertEqual(len(timm_model.stage_names				)   ,				len(transformers_model.stage_names				)				)
           self.assertEqual(timm_model.channels   ,				transformers_model.channels				)
           # Out indices are set to the last layer by default. For timm models, we don't know
           # the number of layers in advance, so we set it to (-1,), whereas for transformers
           # models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
           self.assertEqual(timm_model.out_indices   ,				(-1,)				)
           self.assertEqual(transformers_model.out_indices   ,				[len(timm_model.stage_names				) - 1]				)

           UpperCAmelCase			       =		AutoBackbone.from_pretrained(lowercase   ,				use_timm_backbone=lowercase   ,				out_indices=[1, 2, 3]				)
           UpperCAmelCase			       =		AutoBackbone.from_pretrained(lowercase   ,				out_indices=[1, 2, 3]				)

           self.assertEqual(timm_model.out_indices   ,				transformers_model.out_indices				)
           self.assertEqual(len(timm_model.out_features				)   ,				len(transformers_model.out_features				)				)
           self.assertEqual(timm_model.channels   ,				transformers_model.channels				)
       @unittest.skip('''TimmBackbone doesn\'t support feed forward chunking'''				)
       def     A      (	self						:	int				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute'''				)
       def     A      (	self						:	int				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone initialization is managed on the timm side'''				)
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''				)
       def     A      (	self						:	Union[str, Any]				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''				)
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint'''				)
       def     A      (	self						:	int				):



           '''simple docstring'''

           pass
       @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           pass
       @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''				)
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           pass
       @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''				)
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           pass
       @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''				)
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           pass
       @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''				)
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.'''				)
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           pass
       @unittest.skip('''TimmBackbone doesn\'t support output_attentions.'''				)
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           pass
       @unittest.skip('''Safetensors is not supported by timm.'''				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           pass
       @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''				)
       def     A      (	self						:	int				):



           '''simple docstring'''

           pass
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           UpperCAmelCase       ,     UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               UpperCAmelCase			       =		model_class(lowercase				)
               UpperCAmelCase			       =		inspect.signature(model.forward				)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               UpperCAmelCase			       =		[*signature.parameters.keys()]

               UpperCAmelCase			       =		['''pixel_values''']
               self.assertListEqual(arg_names[:1]   ,				lowercase				)
       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase       ,     UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs_for_common()
           UpperCAmelCase			       =		True
           UpperCAmelCase			       =		self.has_attentions

           # no need to test all models as different heads yield the same functionality
           UpperCAmelCase			       =		self.all_model_classes[0]
           UpperCAmelCase			       =		model_class(lowercase				)
           model.to(lowercase				)

           UpperCAmelCase			       =		self._prepare_for_class(lowercase   ,				lowercase				)
           UpperCAmelCase			       =		model(**lowercase				)
           UpperCAmelCase			       =		outputs[0][-1]

           # Encoder-/Decoder-only models
           UpperCAmelCase			       =		outputs.hidden_states[0]
           hidden_states.retain_grad()

           if self.has_attentions:
               UpperCAmelCase			       =		outputs.attentions[0]
               attentions.retain_grad()

           output.flatten()[0].backward(retain_graph=lowercase				)

           self.assertIsNotNone(hidden_states.grad				)

           if self.has_attentions:
               self.assertIsNotNone(attentions.grad				)







       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           UpperCAmelCase       ,     UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               UpperCAmelCase			       =		model_class(lowercase				)
               model.to(lowercase				)
               model.eval()
               UpperCAmelCase			       =		model(**lowercase				)

               self.assertEqual(len(result.feature_maps				)   ,				len(config.out_indices				)				)
               self.assertEqual(len(model.channels				)   ,				len(config.out_indices				)				)

               # Check output of last stage is taken if out_features=None, out_indices=None
               UpperCAmelCase			       =		copy.deepcopy(lowercase				)
               UpperCAmelCase			       =		None
               UpperCAmelCase			       =		model_class(lowercase				)
               model.to(lowercase				)
               model.eval()
               UpperCAmelCase			       =		model(**lowercase				)

               self.assertEqual(len(result.feature_maps				)   ,				1				)
               self.assertEqual(len(model.channels				)   ,				1				)

               # Check backbone can be initialized with fresh weights
               UpperCAmelCase			       =		copy.deepcopy(lowercase				)
               UpperCAmelCase			       =		False
               UpperCAmelCase			       =		model_class(lowercase				)
               model.to(lowercase				)
               model.eval()
               UpperCAmelCase			       =		model(**lowercase				)










'''simple docstring'''







import math
from typing import Optional

import numpy as np

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


A     =logging.get_logger(__name__)

A     ={
    '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 			_a  (	__a ):
       __a				:     Union[str, Any]   				=					"""encodec"""
       def __init__(	self						:	Tuple   ,				lowercase						:	List[str]=[1.5, 3.0, 6.0, 12.0, 24.0]   ,				lowercase						:	Any=24_000   ,				lowercase						:	str=1   ,				lowercase						:	Optional[int]=False   ,				lowercase						:	Optional[Any]=None   ,				lowercase						:	str=None   ,				lowercase						:	Tuple=128   ,				lowercase						:	Union[str, Any]=32   ,				lowercase						:	Union[str, Any]=1   ,				lowercase						:	Optional[Any]=[8, 5, 4, 2]   ,				lowercase						:	Any="weight_norm"   ,				lowercase						:	Tuple=7   ,				lowercase						:	int=7   ,				lowercase						:	Dict=3   ,				lowercase						:	List[Any]=2   ,				lowercase						:	str=True   ,				lowercase						:	List[str]="reflect"   ,				lowercase						:	List[Any]=2   ,				lowercase						:	Optional[Any]=2   ,				lowercase						:	int=1.0   ,				lowercase						:	Dict=1_024   ,				lowercase						:	str=None   ,				lowercase						:	Union[str, Any]=True   ,				**lowercase						:	Optional[int]   ,				):



           '''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__(**lowercase				)
       @property
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           if self.chunk_length_s is None:
               return None
           else:
               return int(self.chunk_length_s * self.sampling_rate				)
       @property
       def     A      (	self						:	Union[str, Any]				):



           '''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     A      (	self						:	Any				):



           '''simple docstring'''

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







       @property
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

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




