


"""simple docstring"""


import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
    import bitsandbytes as bnb

from copy import deepcopy


__lowerCamelCase      :Any	    =		logging.getLogger(__name__)




def   snake_case		(     UpperCamelCase__       :						List[Any]			,				UpperCamelCase__       :						Union[str, Any]			,				UpperCamelCase__       :						Union[str, Any] = None			,				UpperCamelCase__       :						Optional[Any] = None			,				UpperCamelCase__       :						Optional[int] = None			,				UpperCamelCase__       :						int = None			,				UpperCamelCase__       :						List[str] = None			,				UpperCamelCase__       :						Tuple = False			,				)   ->      str:
      lowerCamelCase					:					List[str]        =	bnb_quantization_config.load_in_abit
      lowerCamelCase					:					str        =	bnb_quantization_config.load_in_abit

      if load_in_abit and not is_abit_bnb_available():
            raise ImportError(
                """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"""
                """ make sure you have the latest version of `bitsandbytes` installed."""    )
      if load_in_abit and not is_abit_bnb_available():
            raise ValueError(
                """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"""
                """make sure you have the latest version of `bitsandbytes` installed."""    )

      lowerCamelCase					:					Optional[int]        =	[]
      # custom device map
      if isinstance(__UpperCamelCase			,				__UpperCamelCase    ) and len(device_map.keys()    ) > 1:
            lowerCamelCase					:					Dict        =	[key for key, value in device_map.items() if value in ["""disk""", """cpu"""]]

      # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
      if bnb_quantization_config.skip_modules is None:
            lowerCamelCase					:					Optional[int]        =	get_keys_to_not_convert(__UpperCamelCase    )

      # add cpu modules to skip modules only for 4-bit modules
      if load_in_abit:
            bnb_quantization_config.skip_modules.extend(__UpperCamelCase    )
      lowerCamelCase					:					Optional[Any]        =	bnb_quantization_config.skip_modules

      # We add the modules we want to keep in full precision
      if bnb_quantization_config.keep_in_fpaa_modules is None:
            lowerCamelCase					:					Dict        =	[]
      lowerCamelCase					:					Union[str, Any]        =	bnb_quantization_config.keep_in_fpaa_modules
      modules_to_not_convert.extend(__UpperCamelCase    )

      # compatibility with peft
      lowerCamelCase					:					Union[str, Any]        =	load_in_abit
      lowerCamelCase					:					Union[str, Any]        =	load_in_abit

      lowerCamelCase					:					Union[str, Any]        =	get_parameter_device(__UpperCamelCase    )
      if model_device.type != "meta":
            # quantization of an already loaded model
            logger.warning(
                """It is not recommended to quantize a loaded model. """
                """The model should be instantiated under the `init_empty_weights` context manager."""    )
            lowerCamelCase					:					str        =	replace_with_bnb_layers(__UpperCamelCase			,				__UpperCamelCase			,				modules_to_not_convert=__UpperCamelCase    )
            # convert param to the right dtype
            lowerCamelCase					:					int        =	bnb_quantization_config.torch_dtype
            for name, param in model.state_dict().items():
                  if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules    ):
                        param.to(torch.floataa    )
                        if param.dtype != torch.floataa:
                              lowerCamelCase					:					Optional[int]        =	name.replace(""".weight"""			,				""""""    ).replace(""".bias"""			,				""""""    )
                              lowerCamelCase					:					Tuple        =	getattr(__UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase    )
                              if param is not None:
                                    param.to(torch.floataa    )
                  elif torch.is_floating_point(__UpperCamelCase    ):
                        param.to(__UpperCamelCase    )
            if model_device.type == "cuda":
                  # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
                  model.cuda(torch.cuda.current_device()    )
                  torch.cuda.empty_cache()
            elif torch.cuda.is_available():
                  model.to(torch.cuda.current_device()    )
            else:
                  raise RuntimeError("""No GPU found. A GPU is needed for quantization."""    )
            logger.info(
                F'The model device type is {model_device.type}. However, cuda is needed for quantization.'
                """We move the model to cuda."""    )
            return model

      elif weights_location is None:
            raise RuntimeError(
                F'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} '    )

      else:
            with init_empty_weights():
                  lowerCamelCase					:					List[Any]        =	replace_with_bnb_layers(
                      __UpperCamelCase			,				__UpperCamelCase			,				modules_to_not_convert=__UpperCamelCase    )

            lowerCamelCase					:					Any        =	get_quantized_model_device_map(
                __UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase			,				max_memory=__UpperCamelCase			,				no_split_module_classes=__UpperCamelCase			,				)
            if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
                  lowerCamelCase					:					Union[str, Any]        =	True

            lowerCamelCase					:					int        =	any(x in list(device_map.values()    ) for x in ["""cpu""", """disk"""]    )

            load_checkpoint_in_model(
                __UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase			,				dtype=bnb_quantization_config.torch_dtype			,				offload_folder=__UpperCamelCase			,				offload_state_dict=__UpperCamelCase			,				keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules			,				offload_abit_bnb=load_in_abit and offload			,				)
            return dispatch_model(__UpperCamelCase			,				device_map=__UpperCamelCase			,				offload_dir=__UpperCamelCase    )




def   snake_case		(     UpperCamelCase__       :						Tuple			,				UpperCamelCase__       :						Optional[Any]			,				UpperCamelCase__       :						str=None			,				UpperCamelCase__       :						Union[str, Any]=None			,				UpperCamelCase__       :						int=None    )   ->      Union[str, Any]:
      if device_map is None:
            if torch.cuda.is_available():
                  lowerCamelCase					:					int        =	{"""""": torch.cuda.current_device()}
            else:
                  raise RuntimeError("""No GPU found. A GPU is needed for quantization."""    )
            logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`."""    )

      if isinstance(__UpperCamelCase			,				__UpperCamelCase    ):
            if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
                  raise ValueError(
                      """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """
                      """'sequential'."""    )

            lowerCamelCase					:					Any        =	{}
            special_dtypes.update(
                {
                    name: bnb_quantization_config.torch_dtype
                    for name, _ in model.named_parameters()
                    if any(m in name for m in bnb_quantization_config.skip_modules    )
                }    )
            special_dtypes.update(
                {
                    name: torch.floataa
                    for name, _ in model.named_parameters()
                    if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules    )
                }    )

            lowerCamelCase					:					List[str]        =	{}
            lowerCamelCase					:					Any        =	special_dtypes
            lowerCamelCase					:					Optional[Any]        =	no_split_module_classes
            lowerCamelCase					:					Dict        =	bnb_quantization_config.target_dtype

            # get max_memory for each device.
            if device_map != "sequential":
                  lowerCamelCase					:					str        =	get_balanced_memory(
                      __UpperCamelCase			,				low_zero=(device_map == """balanced_low_0""")			,				max_memory=__UpperCamelCase			,				**__UpperCamelCase			,				)

            lowerCamelCase					:					Optional[Any]        =	max_memory
            lowerCamelCase					:					int        =	infer_auto_device_map(__UpperCamelCase			,				**__UpperCamelCase    )

      if isinstance(__UpperCamelCase			,				__UpperCamelCase    ):
            # check if don't have any quantized module on the cpu
            lowerCamelCase					:					List[str]        =	bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

            lowerCamelCase					:					Union[str, Any]        =	{
                key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
            }
            for device in ["cpu", "disk"]:
                  if device in device_map_without_some_modules.values():
                        if bnb_quantization_config.load_in_abit:
                              raise ValueError(
                                  """
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        """    )
                        else:
                              logger.info(
                                  """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit"""    )
            del device_map_without_some_modules
      return device_map




def   snake_case		(     UpperCamelCase__       :						Union[str, Any]			,				UpperCamelCase__       :						Dict			,				UpperCamelCase__       :						Optional[Any]=None			,				UpperCamelCase__       :						Tuple=None    )   ->      List[Any]:

      if modules_to_not_convert is None:
            lowerCamelCase					:					Optional[int]        =	[]

      lowerCamelCase     ,			lowerCamelCase					:					Dict        =	_replace_with_bnb_layers(
          __UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase    )
      if not has_been_replaced:
            logger.warning(
                """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
                """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."""
                """ Please double check your model architecture, or submit an issue on github if you think this is"""
                """ a bug."""    )
      return model




def   snake_case		(     UpperCamelCase__       :						List[Any]			,				UpperCamelCase__       :						Dict			,				UpperCamelCase__       :						Union[str, Any]=None			,				UpperCamelCase__       :						List[Any]=None			,				)   ->      int:
      lowerCamelCase					:					Optional[Any]        =	False
      for name, module in model.named_children():
            if current_key_name is None:
                  lowerCamelCase					:					int        =	[]
            current_key_name.append(__UpperCamelCase    )
            if isinstance(__UpperCamelCase			,				nn.Linear    ) and name not in modules_to_not_convert:
                  # Check if the current key is not in the `modules_to_not_convert`
                  lowerCamelCase					:					int        =	""".""".join(__UpperCamelCase    )
                  lowerCamelCase					:					Optional[int]        =	True
                  for key in modules_to_not_convert:
                        if (
                            (key in current_key_name_str) and (key + "." in current_key_name_str)
                        ) or key == current_key_name_str:
                              lowerCamelCase					:					Union[str, Any]        =	False
                              break
                  if proceed:
                        # Load bnb module with empty weight and replace ``nn.Linear` module
                        if bnb_quantization_config.load_in_abit:
                              lowerCamelCase					:					Union[str, Any]        =	bnb.nn.LinearabitLt(
                                  module.in_features			,				module.out_features			,				module.bias is not None			,				has_fpaa_weights=__UpperCamelCase			,				threshold=bnb_quantization_config.llm_inta_threshold			,				)
                        elif bnb_quantization_config.load_in_abit:
                              lowerCamelCase					:					Dict        =	bnb.nn.Linearabit(
                                  module.in_features			,				module.out_features			,				module.bias is not None			,				bnb_quantization_config.bnb_abit_compute_dtype			,				compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant			,				quant_type=bnb_quantization_config.bnb_abit_quant_type			,				)
                        else:
                              raise ValueError("""load_in_8bit and load_in_4bit can't be both False"""    )
                        lowerCamelCase					:					Dict        =	module.weight.data
                        if module.bias is not None:
                              lowerCamelCase					:					Tuple        =	module.bias.data
                        bnb_module.requires_grad_(__UpperCamelCase    )
                        setattr(__UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase    )
                        lowerCamelCase					:					Dict        =	True
            if len(list(module.children()    )    ) > 0:
                  lowerCamelCase     ,			lowerCamelCase					:					Tuple        =	_replace_with_bnb_layers(
                      __UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase    )
                  lowerCamelCase					:					List[str]        =	has_been_replaced | _has_been_replaced
            # Remove the last key for recursion
            current_key_name.pop(-1    )
      return model, has_been_replaced




def   snake_case		(     UpperCamelCase__       :						List[Any]    )   ->      Union[str, Any]:
      # Create a copy of the model
      with init_empty_weights():
            lowerCamelCase					:					str        =	deepcopy(__UpperCamelCase    )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

      lowerCamelCase					:					Any        =	find_tied_parameters(__UpperCamelCase    )
      # For compatibility with Accelerate < 0.18
      if isinstance(__UpperCamelCase			,				__UpperCamelCase    ):
            lowerCamelCase					:					Tuple        =	sum(list(tied_params.values()    )			,				[]    ) + list(tied_params.keys()    )
      else:
            lowerCamelCase					:					int        =	sum(__UpperCamelCase			,				[]    )
      lowerCamelCase					:					Optional[Any]        =	len(__UpperCamelCase    ) > 0

      # Check if it is a base model
      lowerCamelCase					:					int        =	False
      if hasattr(__UpperCamelCase			,				"""base_model_prefix"""    ):
            lowerCamelCase					:					Optional[int]        =	not hasattr(__UpperCamelCase			,				model.base_model_prefix    )

      # Ignore this for base models (BertModel, GPT2Model, etc.)
      if (not has_tied_params) and is_base_model:
            return []

      # otherwise they have an attached head
      lowerCamelCase					:					List[str]        =	list(model.named_children()    )
      lowerCamelCase					:					str        =	[list_modules[-1][0]]

      # add last module together with tied weights
      lowerCamelCase					:					Tuple        =	set(__UpperCamelCase    ) - set(__UpperCamelCase    )
      lowerCamelCase					:					Tuple        =	list(set(__UpperCamelCase    )    ) + list(__UpperCamelCase    )

      # remove ".weight" from the keys
      lowerCamelCase					:					Optional[Any]        =	[""".weight""", """.bias"""]
      lowerCamelCase					:					Tuple        =	[]
      for name in list_untouched:
            for name_to_remove in names_to_remove:
                  if name_to_remove in name:
                        lowerCamelCase					:					Any        =	name.replace(__UpperCamelCase			,				""""""    )
            filtered_module_names.append(__UpperCamelCase    )

      return filtered_module_names




def   snake_case		(     UpperCamelCase__       :						Optional[int]    )   ->      str:
      for m in model.modules():
            if isinstance(__UpperCamelCase			,				bnb.nn.Linearabit    ):
                  return True
      return False




def   snake_case		(     UpperCamelCase__       :						Dict    )   ->      Optional[int]:
      return next(parameter.parameters()    ).device






def   snake_case		(     UpperCamelCase__       :						Optional[Any]			,				UpperCamelCase__       :						Optional[int]			,				UpperCamelCase__       :						Union[str, Any]			,				UpperCamelCase__       :						Tuple			,				UpperCamelCase__       :						Dict			,				UpperCamelCase__       :						int			,				UpperCamelCase__       :						Tuple    )   ->      Union[str, Any]:
      # if it is not quantized, we quantize and offload the quantized weights and the SCB stats
      if fpaa_statistics is None:
            set_module_tensor_to_device(__UpperCamelCase			,				__UpperCamelCase			,				0			,				dtype=__UpperCamelCase			,				value=__UpperCamelCase    )
            lowerCamelCase					:					Any        =	param_name
            lowerCamelCase					:					Any        =	model
            if "." in tensor_name:
                  lowerCamelCase					:					Union[str, Any]        =	tensor_name.split("""."""    )
                  for split in splits[:-1]:
                        lowerCamelCase					:					Tuple        =	getattr(__UpperCamelCase			,				__UpperCamelCase    )
                        if new_module is None:
                              raise ValueError(F'{module} has no attribute {split}.'    )
                        lowerCamelCase					:					Union[str, Any]        =	new_module
                  lowerCamelCase					:					Dict        =	splits[-1]
            # offload weights
            lowerCamelCase					:					Optional[Any]        =	False
            offload_weight(module._parameters[tensor_name]			,				__UpperCamelCase			,				__UpperCamelCase			,				index=__UpperCamelCase    )
            if hasattr(module._parameters[tensor_name]			,				"""SCB"""    ):
                  offload_weight(
                      module._parameters[tensor_name].SCB			,				param_name.replace("""weight"""			,				"""SCB"""    )			,				__UpperCamelCase			,				index=__UpperCamelCase			,				)
      else:
            offload_weight(__UpperCamelCase			,				__UpperCamelCase			,				__UpperCamelCase			,				index=__UpperCamelCase    )
            offload_weight(__UpperCamelCase			,				param_name.replace("""weight"""			,				"""SCB"""    )			,				__UpperCamelCase			,				index=__UpperCamelCase    )

      set_module_tensor_to_device(__UpperCamelCase			,				__UpperCamelCase			,				"""meta"""			,				dtype=__UpperCamelCase			,				value=torch.empty(*param.size()    )    )








"""simple docstring"""


import inspect
import unittest

from transformers import ConvNextConfig
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 transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
    from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class 			A__	:


     """simple docstring"""

     def __init__(	self:						Optional[Any]     ,		__a:						Union[str, Any]     ,		__a:						Optional[Any]=13     ,		__a:						Optional[Any]=32     ,		__a:						Dict=3     ,		__a:						int=4     ,		__a:						Dict=[10, 20, 30, 40]     ,		__a:						int=[2, 2, 3, 2]     ,		__a:						Any=True     ,		__a:						List[Any]=True     ,		__a:						Any=37     ,		__a:						Optional[int]="gelu"     ,		__a:						List[str]=10     ,		__a:						Optional[int]=0.02     ,		__a:						Dict=["stage2", "stage3", "stage4"]     ,		__a:						List[str]=[2, 3, 4]     ,		__a:						List[str]=None     ,		)->    Union[str, Any]:
           lowerCamelCase					:					Optional[int]        =	parent
           lowerCamelCase					:					Optional[int]        =	batch_size
           lowerCamelCase					:					Any        =	image_size
           lowerCamelCase					:					Tuple        =	num_channels
           lowerCamelCase					:					str        =	num_stages
           lowerCamelCase					:					List[str]        =	hidden_sizes
           lowerCamelCase					:					str        =	depths
           lowerCamelCase					:					Dict        =	is_training
           lowerCamelCase					:					Optional[Any]        =	use_labels
           lowerCamelCase					:					List[str]        =	intermediate_size
           lowerCamelCase					:					List[str]        =	hidden_act
           lowerCamelCase					:					List[str]        =	num_labels
           lowerCamelCase					:					Union[str, Any]        =	initializer_range
           lowerCamelCase					:					List[Any]        =	out_features
           lowerCamelCase					:					Optional[Any]        =	out_indices
           lowerCamelCase					:					int        =	scope

     def 		a__						(	self:						str	)->    Optional[Any]:
           lowerCamelCase					:					Union[str, Any]        =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

           lowerCamelCase					:					Any        =	self.get_config()
           return config, pixel_values, labels

     def 		a__						(	self:						Dict	)->    Union[str, Any]:
           return ConvNextConfig(
               num_channels=self.num_channels     ,		hidden_sizes=self.hidden_sizes     ,		depths=self.depths     ,		num_stages=self.num_stages     ,		hidden_act=self.hidden_act     ,		is_decoder=__a     ,		initializer_range=self.initializer_range     ,		out_features=self.out_features     ,		out_indices=self.out_indices     ,		num_labels=self.num_labels     ,		)

     def 		a__						(	self:						Optional[Any]     ,		__a:						List[Any]     ,		__a:						Any     ,		__a:						int	)->    List[Any]:
           lowerCamelCase					:					Optional[int]        =	ConvNextModel(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					Any        =	model(__a	)
           # 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 		a__						(	self:						int     ,		__a:						Union[str, Any]     ,		__a:						List[Any]     ,		__a:						Tuple	)->    Optional[int]:
           lowerCamelCase					:					str        =	ConvNextForImageClassification(__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					Any        =	model(__a     ,		labels=__a	)
           self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.num_labels)	)

     def 		a__						(	self:						List[Any]     ,		__a:						Any     ,		__a:						Optional[int]     ,		__a:						Tuple	)->    List[str]:
           lowerCamelCase					:					List[str]        =	ConvNextBackbone(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					int        =	model(__a	)

           # verify hidden states
           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
           lowerCamelCase					:					Tuple        =	None
           lowerCamelCase					:					List[str]        =	ConvNextBackbone(config=__a	)
           model.to(__a	)
           model.eval()
           lowerCamelCase					:					List[Any]        =	model(__a	)

           # 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 		a__						(	self:						Optional[Any]	)->    Any:
           lowerCamelCase					:					List[Any]        =	self.prepare_config_and_inputs()
           lowerCamelCase     ,			lowerCamelCase     ,			lowerCamelCase					:					Tuple        =	config_and_inputs
           lowerCamelCase					:					int        =	{"""pixel_values""": pixel_values}
           return config, inputs_dict


@require_torch
class 			A__	(						__lowercase ,     __lowercase ,     unittest.TestCase):


     """simple docstring"""
     snake_case__	:					int													=(
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     snake_case__	:					str													=(
         {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     snake_case__	:					Union[str, Any]													=True
     snake_case__	:					Optional[int]													=False
     snake_case__	:					Tuple													=False
     snake_case__	:					Union[str, Any]													=False
     snake_case__	:					Tuple													=False

     def 		a__						(	self:						Optional[Any]	)->    Union[str, Any]:
           lowerCamelCase					:					Tuple        =	ConvNextModelTester(self	)
           lowerCamelCase					:					List[Any]        =	ConfigTester(self     ,		config_class=__a     ,		has_text_modality=__a     ,		hidden_size=37	)

     def 		a__						(	self:						Optional[int]	)->    Dict:
           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 		a__						(	self:						Optional[int]	)->    Optional[Any]:
           return

     @unittest.skip(reason="""ConvNext does not use inputs_embeds"""	)
     def 		a__						(	self:						int	)->    Dict:
           pass

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

     @unittest.skip(reason="""ConvNext does not use feedforward chunking"""	)
     def 		a__						(	self:						int	)->    List[Any]:
           pass

     def 		a__						(	self:						Union[str, Any]	)->    int:
           lowerCamelCase     ,			lowerCamelCase					:					List[str]        =	self.model_tester.prepare_config_and_inputs_for_common()

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

                 lowerCamelCase					:					List[str]        =	["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]     ,		__a	)

     def 		a__						(	self:						Optional[int]	)->    str:
           lowerCamelCase					:					Any        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__a	)

     def 		a__						(	self:						str	)->    int:
           lowerCamelCase					:					int        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*__a	)

     def 		a__						(	self:						int	)->    Optional[int]:
           def check_hidden_states_output(__a:						Tuple     ,		__a:						int     ,		__a:						Tuple	):
                 lowerCamelCase					:					str        =	model_class(__a	)
                 model.to(__a	)
                 model.eval()

                 with torch.no_grad():
                       lowerCamelCase					:					Tuple        =	model(**self._prepare_for_class(__a     ,		__a	)	)

                 lowerCamelCase					:					int        =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 lowerCamelCase					:					Optional[int]        =	self.model_tester.num_stages
                 self.assertEqual(len(__a	)     ,		expected_num_stages + 1	)

                 # ConvNext'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]     ,		)

           lowerCamelCase     ,			lowerCamelCase					:					List[Any]        =	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 lowerCamelCase					:					List[Any]        =	True
                 check_hidden_states_output(__a     ,		__a     ,		__a	)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 lowerCamelCase					:					Tuple        =	True

                 check_hidden_states_output(__a     ,		__a     ,		__a	)

     def 		a__						(	self:						Dict	)->    Optional[Any]:
           lowerCamelCase					:					List[str]        =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__a	)







     @slow
     def 		a__						(	self:						Optional[Any]	)->    Tuple:
           for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase					:					str        =	ConvNextModel.from_pretrained(__a	)
                 self.assertIsNotNone(__a	)




def   snake_case		(     )   ->      Optional[int]:
      lowerCamelCase					:					int        =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
      return image


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


     """simple docstring"""

     @cached_property
     def 		a__						(	self:						Dict	)->    Union[str, Any]:
           return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""	) if is_vision_available() else None







     @slow
     def 		a__						(	self:						List[str]	)->    Dict:
           lowerCamelCase					:					Tuple        =	ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""	).to(__a	)

           lowerCamelCase					:					Dict        =	self.default_image_processor
           lowerCamelCase					:					Union[str, Any]        =	prepare_img()
           lowerCamelCase					:					Optional[Any]        =	image_processor(images=__a     ,		return_tensors="""pt"""	).to(__a	)

           # forward pass
           with torch.no_grad():
                 lowerCamelCase					:					Any        =	model(**__a	)

           # verify the logits
           lowerCamelCase					:					Union[str, Any]        =	torch.Size((1, 1_000)	)
           self.assertEqual(outputs.logits.shape     ,		__a	)

           lowerCamelCase					:					Tuple        =	torch.tensor([-0.02_60, -0.47_39, 0.19_11]	).to(__a	)

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


@require_torch
class 			A__	(						unittest.TestCase ,     __lowercase):


     """simple docstring"""
     snake_case__	:					Union[str, Any]													=(ConvNextBackbone,) if is_torch_available() else ()
     snake_case__	:					Optional[Any]													=ConvNextConfig

     snake_case__	:					Optional[Any]													=False

     def 		a__						(	self:						List[str]	)->    int:
           lowerCamelCase					:					Dict        =	ConvNextModelTester(self	)




