






# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__UpperCamelCase   :   Optional[Any]      =    Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__UpperCamelCase   :   str      =    {"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

__UpperCamelCase   :   List[str]      =    """zero2"""
__UpperCamelCase   :   List[Any]      =    """zero3"""
__UpperCamelCase   :   Optional[int]      =    [ZEROa, ZEROa]





def 					snake_case	(  lowerCamelCase					,	lowerCamelCase					,	lowerCamelCase       ):




	'''simple docstring'''







	__lowercase   							=	parameterized.to_safe_name("""_""".join(str(lowerCamelCase       ) for x in param.args       )       )
	return F'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
__UpperCamelCase   :   Union[str, Any]      =    list(itertools.product(stages, models.keys()))




@slow
@require_deepspeed
@require_torch_gpu
class 							__UpperCamelCase     (  _lowerCAmelCase ):







	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				Dict							,					_lowerCAmelCase   :				int							,					_lowerCAmelCase   :				Dict      )		->			Union[str, Any]:
		"""simple docstring"""







		self.run_and_check(
		    stage=_lowerCAmelCase							,					model=_lowerCAmelCase							,					distributed=_lowerCAmelCase							,					fpaa=_lowerCAmelCase							,					)







	@require_torch_multi_gpu
	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				Optional[int]							,					_lowerCAmelCase   :				Dict							,					_lowerCAmelCase   :				List[Any]      )		->			Tuple:
		"""simple docstring"""







		self.run_and_check(
		    stage=_lowerCAmelCase							,					model=_lowerCAmelCase							,					distributed=_lowerCAmelCase							,					fpaa=_lowerCAmelCase							,					)







	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				Tuple							,					_lowerCAmelCase   :				Dict							,					_lowerCAmelCase   :				Tuple      )		->			Optional[Any]:
		"""simple docstring"""







		self.run_and_check(
		    stage=_lowerCAmelCase							,					model=_lowerCAmelCase							,					distributed=_lowerCAmelCase							,					fpaa=_lowerCAmelCase							,					)







	@require_torch_multi_gpu
	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				str							,					_lowerCAmelCase   :				Optional[Any]							,					_lowerCAmelCase   :				Dict      )		->			str:
		"""simple docstring"""







		self.run_and_check(
		    stage=_lowerCAmelCase							,					model=_lowerCAmelCase							,					distributed=_lowerCAmelCase							,					fpaa=_lowerCAmelCase							,					)







	def 			_a (	self   :				Union[str, Any]							,					_lowerCAmelCase   :				Optional[Any]      )		->			Any:
		"""simple docstring"""







		pass







	def 			_a (	self   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				int = 10							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					)		->			str:
		"""simple docstring"""







		__lowercase   							=	models[model]

		__lowercase   							=	self.run_trainer(
		    stage=_lowerCAmelCase							,					model_name=_lowerCAmelCase							,					eval_steps=_lowerCAmelCase							,					num_train_epochs=1							,					distributed=_lowerCAmelCase							,					fpaa=_lowerCAmelCase							,					)

		self.do_checks(_lowerCAmelCase      )

		return output_dir







	def 			_a (	self   :				List[str]							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				int = 10							,					_lowerCAmelCase   :				int = 1							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					)		->			Dict:
		"""simple docstring"""







		__lowercase   							=	self.get_auto_remove_tmp_dir("""./xxx"""							,					after=_lowerCAmelCase      )
		__lowercase   							=	F'\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(_lowerCAmelCase      )}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        '.split()

		if fpaa:
			args.extend(["""--fp16"""]      )

		# currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
		# hence the separate config files
		__lowercase   							=	F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
		__lowercase   							=	[F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
		__lowercase   							=	self.get_launcher(_lowerCAmelCase      )

		__lowercase   							=	launcher + script + args + ds_args
		# keep for quick debug
		# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
		execute_subprocess_async(_lowerCAmelCase							,					env=self.get_env()      )

		return output_dir







	def 			_a (	self   :				List[str]							,					_lowerCAmelCase   :				str=False      )		->			Dict:
		"""simple docstring"""







		__lowercase   							=	min(2							,					get_gpu_count()      ) if distributed else 1
		return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()




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

  def __init__(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=13      , _SCREAMING_SNAKE_CASE=32      , _SCREAMING_SNAKE_CASE=3      , _SCREAMING_SNAKE_CASE=4      , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40]      , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2]      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=37      , _SCREAMING_SNAKE_CASE="gelu"      , _SCREAMING_SNAKE_CASE=10      , _SCREAMING_SNAKE_CASE=0.02      , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"]      , _SCREAMING_SNAKE_CASE=[2, 3, 4]      , _SCREAMING_SNAKE_CASE=None      , ):





      '''simple docstring'''

      lowerCAmelCase 						=							parent
      lowerCAmelCase 						=							batch_size
      lowerCAmelCase 						=							image_size
      lowerCAmelCase 						=							num_channels
      lowerCAmelCase 						=							num_stages
      lowerCAmelCase 						=							hidden_sizes
      lowerCAmelCase 						=							depths
      lowerCAmelCase 						=							is_training
      lowerCAmelCase 						=							use_labels
      lowerCAmelCase 						=							intermediate_size
      lowerCAmelCase 						=							hidden_act
      lowerCAmelCase 						=							num_labels
      lowerCAmelCase 						=							initializer_range
      lowerCAmelCase 						=							out_features
      lowerCAmelCase 						=							out_indices
      lowerCAmelCase 						=							scope

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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

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

      lowerCAmelCase 						=							self.get_config()
      return config, pixel_values, labels

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      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=_SCREAMING_SNAKE_CASE      , initializer_range=self.initializer_range      , out_features=self.out_features      , out_indices=self.out_indices      , num_labels=self.num_labels      , )

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModel(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification(_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE      , labels=_SCREAMING_SNAKE_CASE	)
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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
      lowerCAmelCase 						=							None
      lowerCAmelCase 						=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							model(_SCREAMING_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   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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



@require_torch
class 				_snake_case					(   a_     , a_     , unittest.TestCase			):
  SCREAMING_SNAKE_CASE			:       List[Any]				=     (
      (
          ConvNextModel,
          ConvNextForImageClassification,
          ConvNextBackbone,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE			:       int				=     (
      {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
      if is_torch_available()
      else {}
  )

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

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)
      lowerCAmelCase 						=							ConfigTester(self      , config_class=_SCREAMING_SNAKE_CASE      , has_text_modality=_SCREAMING_SNAKE_CASE      , hidden_size=37	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





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





      '''simple docstring'''

      return

  @unittest.skip(reason='ConvNext does not use inputs_embeds'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

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





      '''simple docstring'''

      pass

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





      '''simple docstring'''

      pass

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase						,   lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase 						=							['pixel_values']
          self.assertListEqual(arg_names[:1]      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      def check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          lowerCAmelCase 						=							model_class(_SCREAMING_SNAKE_CASE	)
          model.to(_SCREAMING_SNAKE_CASE	)
          model.eval()

          with torch.no_grad():
              lowerCAmelCase 						=							model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)	)

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

          lowerCAmelCase 						=							self.model_tester.num_stages
          self.assertEqual(len(_SCREAMING_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]      , )

      lowerCAmelCase						,   lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          lowerCAmelCase 						=							True
          check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

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

          check_hidden_states_output(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE	)


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase 						=							ConvNextModel.from_pretrained(_SCREAMING_SNAKE_CASE	)
          self.assertIsNotNone(_SCREAMING_SNAKE_CASE	)



def       snake_case   (	) ->  List[str]:


    """simple docstring"""


    lowerCAmelCase 						=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
    return image



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

  @cached_property
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'	) if is_vision_available() else None


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'	).to(_SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							self.default_image_processor
      lowerCAmelCase 						=							prepare_img()
      lowerCAmelCase 						=							image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors='pt'	).to(_SCREAMING_SNAKE_CASE	)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase 						=							model(**_SCREAMING_SNAKE_CASE	)

      # verify the logits
      lowerCAmelCase 						=							torch.Size((1, 10_00)	)
      self.assertEqual(outputs.logits.shape      , _SCREAMING_SNAKE_CASE	)

      lowerCAmelCase 						=							torch.tensor([-0.0_260, -0.4_739, 0.1_911]	).to(_SCREAMING_SNAKE_CASE	)

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



@require_torch
class 				_snake_case					(   unittest.TestCase     , a_			):
  SCREAMING_SNAKE_CASE			:       Dict				=     (ConvNextBackbone,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE			:       Tuple				=     ConvNextConfig

  SCREAMING_SNAKE_CASE			:       Dict				=     False

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							ConvNextModelTester(self	)





