



'''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__:







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







    def     lowercase_ (   self				:						Union[str, Any]			):
      a		:      Tuple       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      a		:      Union[str, Any]       =  None
      if self.use_labels:
        a		:      Dict       =  ids_tensor([self.batch_size]		,    self.num_labels			)

      a		:      Optional[int]       =  self.get_config()
      return config, pixel_values, labels







    def     lowercase_ (   self				:						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=__snake_case		,    initializer_range=self.initializer_range		,    out_features=self.out_features		,    out_indices=self.out_indices		,    num_labels=self.num_labels		,    )







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







    def     lowercase_ (   self				:						Tuple		,    __snake_case				:						List[str]		,    __snake_case				:						List[Any]		,    __snake_case				:						str			):
      a		:      List[str]       =  ConvNextBackbone(config=__snake_case			)
      model.to(__snake_case			)
      model.eval()
      a		:      Any       =  model(__snake_case			)

      # 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
      a		:      Any       =  None
      a		:      Optional[int]       =  ConvNextBackbone(config=__snake_case			)
      model.to(__snake_case			)
      model.eval()
      a		:      Optional[Any]       =  model(__snake_case			)

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

@require_torch
class 							a__(      lowerCamelCase__	,				lowerCamelCase__	,				unittest.TestCase			):
    lowercase__				=					(
        (
            ConvNextModel,
            ConvNextForImageClassification,
            ConvNextBackbone,
        )
        if is_torch_available()
        else ()
    )
    lowercase__				=					(
        {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
        if is_torch_available()
        else {}
    )

    lowercase__				=					True
    lowercase__				=					False
    lowercase__				=					False
    lowercase__				=					False
    lowercase__				=					False







    def     lowercase_ (   self				:						Any			):
      a		:      List[str]       =  ConvNextModelTester(self			)
      a		:      Union[str, Any]       =  ConfigTester(self		,    config_class=__snake_case		,    has_text_modality=__snake_case		,    hidden_size=37			)







    def     lowercase_ (   self				:						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     lowercase_ (   self				:						Union[str, Any]			):
      return







    @unittest.skip(reason='ConvNext does not use inputs_embeds'			)
    def     lowercase_ (   self				:						Union[str, Any]			):
      pass







    @unittest.skip(reason='ConvNext does not support input and output embeddings'			)
    def     lowercase_ (   self				:						str			):
      pass







    @unittest.skip(reason='ConvNext does not use feedforward chunking'			)
    def     lowercase_ (   self				:						Any			):
      pass







    def     lowercase_ (   self				:						Dict			):
      a     ,			a		:      str       =  self.model_tester.prepare_config_and_inputs_for_common()

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

        a		:      str       =  ['pixel_values']
        self.assertListEqual(arg_names[:1]		,    __snake_case			)







    def     lowercase_ (   self				:						Optional[int]			):
      a		:      Dict       =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__snake_case			)







    def     lowercase_ (   self				:						Optional[Any]			):
      a		:      Optional[Any]       =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      def check_hidden_states_output(__snake_case				:						Union[str, Any]		,    __snake_case				:						Any		,    __snake_case				:						Optional[Any]			):
        a		:      str       =  model_class(__snake_case			)
        model.to(__snake_case			)
        model.eval()

        with torch.no_grad():
          a		:      int       =  model(**self._prepare_for_class(__snake_case		,    __snake_case			)			)

        a		:      Union[str, Any]       =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        a		:      Optional[Any]       =  self.model_tester.num_stages
        self.assertEqual(len(__snake_case			)		,    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]		,    )

      a     ,			a		:      List[str]       =  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a		:      Any       =  True
        check_hidden_states_output(__snake_case		,    __snake_case		,    __snake_case			)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        a		:      Optional[Any]       =  True

        check_hidden_states_output(__snake_case		,    __snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Any			):
      a		:      Any       =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__snake_case			)







    @slow
    def     lowercase_ (   self				:						Optional[Any]			):
      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a		:      Tuple       =  ConvNextModel.from_pretrained(__snake_case			)
        self.assertIsNotNone(__snake_case			)
def    lowerCamelCase__ (		):
  a		:      str       =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
  return image

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







    @cached_property
    def     lowercase_ (   self				:						List[Any]			):
      return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'			) if is_vision_available() else None







    @slow
    def     lowercase_ (   self				:						int			):
      a		:      List[str]       =  ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'			).to(__snake_case			)

      a		:      Any       =  self.default_image_processor
      a		:      Optional[int]       =  prepare_img()
      a		:      str       =  image_processor(images=__snake_case		,    return_tensors='pt'			).to(__snake_case			)

      # forward pass
      with torch.no_grad():
        a		:      int       =  model(**__snake_case			)

      # verify the logits
      a		:      int       =  torch.Size((1, 10_00)			)
      self.assertEqual(outputs.logits.shape		,    __snake_case			)

      a		:      List[Any]       =  torch.tensor([-0.0260, -0.4739, 0.1911]			).to(__snake_case			)

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

@require_torch
class 							a__(      unittest.TestCase	,				lowerCamelCase__			):
    lowercase__				=					(ConvNextBackbone,) if is_torch_available() else ()
    lowercase__				=					ConvNextConfig

    lowercase__				=					False







    def     lowercase_ (   self				:						int			):
      a		:      Dict       =  ConvNextModelTester(self			)




'''simple docstring'''






import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def    lowerCamelCase__ (		_A       ):
  return EnvironmentCommand()

class 							a__(      lowerCamelCase__			):







    @staticmethod
    def     lowercase_ (   __snake_case				:						ArgumentParser			):
      a		:      Tuple       =  parser.add_parser('env'			)
      download_parser.set_defaults(func=__snake_case			)







    def     lowercase_ (   self				:						List[str]			):
      a		:      str       =  huggingface_hub.__version__

      a		:      List[str]       =  'not installed'
      a		:      List[str]       =  'NA'
      if is_torch_available():
        import torch

        a		:      Optional[Any]       =  torch.__version__
        a		:      int       =  torch.cuda.is_available()

      a		:      Optional[int]       =  'not installed'
      if is_transformers_available():
        import transformers

        a		:      Tuple       =  transformers.__version__

      a		:      Dict       =  'not installed'
      if is_accelerate_available():
        import accelerate

        a		:      int       =  accelerate.__version__

      a		:      Any       =  'not installed'
      if is_xformers_available():
        import xformers

        a		:      Optional[int]       =  xformers.__version__

      a		:      List[str]       =  {
          '`diffusers` version': version,
          'Platform': platform.platform(),
          'Python version': platform.python_version(),
          'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""",
          'Huggingface_hub version': hub_version,
          'Transformers version': transformers_version,
          'Accelerate version': accelerate_version,
          'xFormers version': xformers_version,
          'Using GPU in script?': '<fill in>',
          'Using distributed or parallel set-up in script?': '<fill in>',
      }

      print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'			)
      print(self.format_dict(__snake_case			)			)

      return info







    @staticmethod
    def     lowercase_ (   __snake_case				:						Union[str, Any]			):
      return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()]			) + "\n"