




'''simple docstring'''
import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
  from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class        SCREAMING_SNAKE_CASE:

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=3					,		lowerCamelCase__=32					,		lowerCamelCase__=3					,		lowerCamelCase__=10					,		lowerCamelCase__=[10, 20, 30, 40]					,		lowerCamelCase__=[1, 1, 2, 1]					,		lowerCamelCase__=True					,		lowerCamelCase__=True					,		lowerCamelCase__="relu"					,		lowerCamelCase__=3					,		lowerCamelCase__=None					,		lowerCamelCase__=["stage2", "stage3", "stage4"]					,		lowerCamelCase__=[2, 3, 4]					,		)    ->					Dict:

           """simple docstring"""



           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						image_size
           __lowercase							=						num_channels
           __lowercase							=						embeddings_size
           __lowercase							=						hidden_sizes
           __lowercase							=						depths
           __lowercase							=						is_training
           __lowercase							=						use_labels
           __lowercase							=						hidden_act
           __lowercase							=						num_labels
           __lowercase							=						scope
           __lowercase							=						len(lowerCamelCase__     )
           __lowercase							=						out_features
           __lowercase							=						out_indices

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

           """simple docstring"""



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

           __lowercase							=						None
           if self.use_labels:
               __lowercase							=						ids_tensor([self.batch_size]					,		self.num_labels     )

           __lowercase							=						self.get_config()

           return config, pixel_values, labels

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return ResNetConfig(
               num_channels=self.num_channels					,		embeddings_size=self.embeddings_size					,		hidden_sizes=self.hidden_sizes					,		depths=self.depths					,		hidden_act=self.hidden_act					,		num_labels=self.num_labels					,		out_features=self.out_features					,		out_indices=self.out_indices					,		)

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						ResNetModel(config=lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__     )
           # expected last hidden states: B, C, H // 32, W // 32
           self.parent.assertEqual(
               result.last_hidden_state.shape					,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)					,		)

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						self.num_labels
           __lowercase							=						ResNetForImageClassification(lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__					,		labels=lowerCamelCase__     )
           self.parent.assertEqual(result.logits.shape					,		(self.batch_size, self.num_labels)     )

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					str:

           """simple docstring"""



           __lowercase							=						ResNetBackbone(config=lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__     )

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps     )					,		len(config.out_features     )     )
           self.parent.assertListEqual(list(result.feature_maps[0].shape     )					,		[self.batch_size, self.hidden_sizes[1], 4, 4]     )

           # verify channels
           self.parent.assertEqual(len(model.channels     )					,		len(config.out_features     )     )
           self.parent.assertListEqual(model.channels					,		config.hidden_sizes[1:]     )

           # verify backbone works with out_features=None
           __lowercase							=						None
           __lowercase							=						ResNetBackbone(config=lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__     )

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps     )					,		1     )
           self.parent.assertListEqual(list(result.feature_maps[0].shape     )					,		[self.batch_size, self.hidden_sizes[-1], 1, 1]     )

           # verify channels
           self.parent.assertEqual(len(model.channels     )					,		1     )
           self.parent.assertListEqual(model.channels					,		[config.hidden_sizes[-1]]     )




       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						self.prepare_config_and_inputs()
           __lowercase				,__lowercase				,__lowercase							=						config_and_inputs
           __lowercase							=						{"""pixel_values""": pixel_values}
           return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE(				__A   ,      __A   ,      unittest.TestCase     ):
       snake_case_ :     Any    =					(
           (
               ResNetModel,
               ResNetForImageClassification,
               ResNetBackbone,
           )
           if is_torch_available()
           else ()
       )
       snake_case_ :     int    =					(
           {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
           if is_torch_available()
           else {}
       )

       snake_case_ :     Dict    =					True
       snake_case_ :     Dict    =					False
       snake_case_ :     List[str]    =					False
       snake_case_ :     Optional[int]    =					False
       snake_case_ :     str    =					False

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

           """simple docstring"""



           __lowercase							=						ResNetModelTester(self     )
           __lowercase							=						ConfigTester(self					,		config_class=lowerCamelCase__					,		has_text_modality=lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           self.create_and_test_config_common_properties()
           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     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return

       @unittest.skip(reason="""ResNet does not use inputs_embeds"""     )
       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           pass

       @unittest.skip(reason="""ResNet does not support input and output embeddings"""     )
       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           pass

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

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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

               __lowercase							=						["""pixel_values"""]
               self.assertListEqual(arg_names[:1]					,		lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __lowercase							=						model_class(config=lowerCamelCase__     )
               for name, module in model.named_modules():
                   if isinstance(lowerCamelCase__					,		(nn.BatchNormad, nn.GroupNorm)     ):
                       self.assertTrue(
                           torch.all(module.weight == 1     )					,		msg=F'Parameter {name} of model {model_class} seems not properly initialized'					,		)
                       self.assertTrue(
                           torch.all(module.bias == 0     )					,		msg=F'Parameter {name} of model {model_class} seems not properly initialized'					,		)

       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           def check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     ):
               __lowercase							=						model_class(lowerCamelCase__     )
               model.to(lowerCamelCase__     )
               model.eval()

               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )     )

               __lowercase							=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               __lowercase							=						self.model_tester.num_stages
               self.assertEqual(len(lowerCamelCase__     )					,		expected_num_stages + 1     )

               # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]     )					,		[self.model_tester.image_size // 4, self.model_tester.image_size // 4]					,		)

           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
           __lowercase							=						["""basic""", """bottleneck"""]
           for model_class in self.all_model_classes:
               for layer_type in layers_type:
                   __lowercase							=						layer_type
                   __lowercase							=						True
                   check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   __lowercase							=						True

                   check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

       @unittest.skip(reason="""ResNet does not use feedforward chunking"""     )
       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           pass

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

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__     )




       @slow
       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __lowercase							=						ResNetModel.from_pretrained(lowerCamelCase__     )
               self.assertIsNotNone(lowerCamelCase__     )

def 				snake_case_  (   ):



    """simple docstring"""




    __lowercase							=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
    return image






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       @cached_property
       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           return (
               AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
               if is_vision_available()
               else None
           )




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

           """simple docstring"""



           __lowercase							=						ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(lowerCamelCase__     )

           __lowercase							=						self.default_image_processor
           __lowercase							=						prepare_img()
           __lowercase							=						image_processor(images=lowerCamelCase__					,		return_tensors="""pt"""     ).to(lowerCamelCase__     )

           # forward pass
           with torch.no_grad():
               __lowercase							=						model(**lowerCamelCase__     )

           # verify the logits
           __lowercase							=						torch.Size((1, 1000)     )
           self.assertEqual(outputs.logits.shape					,		lowerCamelCase__     )

           __lowercase							=						torch.tensor([-11.10_69, -9.78_77, -8.37_77]     ).to(lowerCamelCase__     )

           self.assertTrue(torch.allclose(outputs.logits[0, :3]					,		lowerCamelCase__					,		atol=1E-4     )     )






@require_torch
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Tuple    =					(ResNetBackbone,) if is_torch_available() else ()
       snake_case_ :     Optional[Any]    =					False
       snake_case_ :     str    =					ResNetConfig

       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           __lowercase							=						ResNetModelTester(self     )










'''simple docstring'''
import copy
from typing import Dict

from ...generation.configuration_utils import GenerationConfig
from ...utils import logging


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






class        SCREAMING_SNAKE_CASE(				__A     ):
       snake_case_ :     List[Any]    =					"""semantic"""

       def __init__(    self					,		lowerCamelCase__=1_0000					,		lowerCamelCase__=True					,		lowerCamelCase__=768					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=0.7					,		lowerCamelCase__=True					,		lowerCamelCase__=1_0048					,		lowerCamelCase__=12_9595					,		lowerCamelCase__=12_9599					,		lowerCamelCase__=1_0000					,		lowerCamelCase__=256					,		lowerCamelCase__=49.9					,		**lowerCamelCase__					,		)    ->					List[Any]:

           """simple docstring"""



           super().__init__(
               temperature=lowerCamelCase__					,		do_sample=lowerCamelCase__					,		eos_token_id=lowerCamelCase__					,		renormalize_logits=lowerCamelCase__					,		max_new_tokens=lowerCamelCase__					,		output_scores=lowerCamelCase__					,		return_dict_in_generate=lowerCamelCase__					,		output_hidden_states=lowerCamelCase__					,		output_attentions=lowerCamelCase__					,		**lowerCamelCase__					,		)

           __lowercase							=						text_encoding_offset
           __lowercase							=						text_pad_token
           __lowercase							=						eos_token_id
           __lowercase							=						semantic_infer_token
           __lowercase							=						semantic_vocab_size
           __lowercase							=						max_input_semantic_length
           __lowercase							=						semantic_rate_hz






class        SCREAMING_SNAKE_CASE(				__A     ):
       snake_case_ :     Optional[int]    =					"""coarse_acoustics"""

       def __init__(    self					,		lowerCamelCase__=True					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=0.7					,		lowerCamelCase__=True					,		lowerCamelCase__=1_2048					,		lowerCamelCase__=75					,		lowerCamelCase__=2					,		lowerCamelCase__=1_2050					,		lowerCamelCase__=256					,		lowerCamelCase__ = 630					,		lowerCamelCase__ = 60					,		**lowerCamelCase__					,		)    ->					Dict:

           """simple docstring"""



           super().__init__(
               temperature=lowerCamelCase__					,		do_sample=lowerCamelCase__					,		renormalize_logits=lowerCamelCase__					,		output_scores=lowerCamelCase__					,		return_dict_in_generate=lowerCamelCase__					,		output_hidden_states=lowerCamelCase__					,		output_attentions=lowerCamelCase__					,		**lowerCamelCase__					,		)

           __lowercase							=						coarse_semantic_pad_token
           __lowercase							=						coarse_rate_hz
           __lowercase							=						n_coarse_codebooks
           __lowercase							=						coarse_infer_token
           __lowercase							=						max_coarse_input_length
           __lowercase							=						max_coarse_history
           __lowercase							=						sliding_window_len






class        SCREAMING_SNAKE_CASE(				__A     ):
       snake_case_ :     Optional[Any]    =					"""fine_acoustics"""

       def __init__(    self					,		lowerCamelCase__=0.5					,		lowerCamelCase__=512					,		lowerCamelCase__=1024					,		lowerCamelCase__=8					,		**lowerCamelCase__					,		)    ->					str:

           """simple docstring"""



           super().__init__(temperature=lowerCamelCase__     )

           __lowercase							=						max_fine_history_length
           __lowercase							=						max_fine_input_length
           __lowercase							=						n_fine_codebooks






class        SCREAMING_SNAKE_CASE(				__A     ):
       snake_case_ :     Optional[Any]    =					"""bark"""
       snake_case_ :     Dict    =					True

       def __init__(    self					,		lowerCamelCase__ = None					,		lowerCamelCase__ = None					,		lowerCamelCase__ = None					,		lowerCamelCase__=2_4000					,		lowerCamelCase__=1024					,		**lowerCamelCase__					,		)    ->					Optional[int]:

           """simple docstring"""



           if semantic_config is None:
               __lowercase							=						{}
               logger.info("""semantic_config is None. initializing the semantic model with default values."""     )

           if coarse_acoustics_config is None:
               __lowercase							=						{}
               logger.info("""coarse_acoustics_config is None. initializing the coarse model with default values."""     )

           if fine_acoustics_config is None:
               __lowercase							=						{}
               logger.info("""fine_acoustics_config is None. initializing the fine model with default values."""     )

           __lowercase							=						BarkSemanticGenerationConfig(**lowerCamelCase__     )
           __lowercase							=						BarkCoarseGenerationConfig(**lowerCamelCase__     )
           __lowercase							=						BarkFineGenerationConfig(**lowerCamelCase__     )

           __lowercase							=						sample_rate
           __lowercase							=						codebook_size

       @classmethod
       def     snake_case__			(    cls					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		**lowerCamelCase__					,		)    ->					Union[str, Any]:

           """simple docstring"""



           return cls(
               semantic_config=semantic_config.to_dict()					,		coarse_acoustics_config=coarse_acoustics_config.to_dict()					,		fine_acoustics_config=fine_acoustics_config.to_dict()					,		**lowerCamelCase__					,		)




       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						copy.deepcopy(self.__dict__     )

           __lowercase							=						self.semantic_config.to_dict()
           __lowercase							=						self.coarse_acoustics_config.to_dict()
           __lowercase							=						self.fine_acoustics_config.to_dict()

           __lowercase							=						self.__class__.model_type
           return output




