





'''simple docstring'''

import unittest

from transformers import LayoutLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       LayoutLMForMaskedLM,
       LayoutLMForQuestionAnswering,
       LayoutLMForSequenceClassification,
       LayoutLMForTokenClassification,
       LayoutLMModel,
   )





class lowerCamelCase    :







  def __init__(		self  ,  lowercase__  ,  lowercase__=13  ,  lowercase__=7  ,  lowercase__=True  ,  lowercase__=True  ,  lowercase__=True  ,  lowercase__=True  ,  lowercase__=99  ,  lowercase__=32  ,  lowercase__=5  ,  lowercase__=4  ,  lowercase__=37  ,  lowercase__="gelu"  ,  lowercase__=0.1  ,  lowercase__=0.1  ,  lowercase__=512  ,  lowercase__=16  ,  lowercase__=2  ,  lowercase__=0.02  ,  lowercase__=3  ,  lowercase__=4  ,  lowercase__=None  ,  lowercase__=1_000  ,  )		->    List[str]:






        """simple docstring"""





        _snake_case		:						int         =  parent
        _snake_case		:						Dict         =  batch_size
        _snake_case		:						str         =  seq_length
        _snake_case		:						str         =  is_training
        _snake_case		:						str         =  use_input_mask
        _snake_case		:						Optional[int]         =  use_token_type_ids
        _snake_case		:						Optional[int]         =  use_labels
        _snake_case		:						str         =  vocab_size
        _snake_case		:						str         =  hidden_size
        _snake_case		:						Any         =  num_hidden_layers
        _snake_case		:						Union[str, Any]         =  num_attention_heads
        _snake_case		:						Optional[int]         =  intermediate_size
        _snake_case		:						List[Any]         =  hidden_act
        _snake_case		:						int         =  hidden_dropout_prob
        _snake_case		:						List[Any]         =  attention_probs_dropout_prob
        _snake_case		:						int         =  max_position_embeddings
        _snake_case		:						List[Any]         =  type_vocab_size
        _snake_case		:						Dict         =  type_sequence_label_size
        _snake_case		:						Union[str, Any]         =  initializer_range
        _snake_case		:						Optional[Any]         =  num_labels
        _snake_case		:						Optional[Any]         =  num_choices
        _snake_case		:						str         =  scope
        _snake_case		:						List[str]         =  range_bbox







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






        """simple docstring"""





        _snake_case		:						Tuple         =  ids_tensor([self.batch_size, self.seq_length]  ,  self.vocab_size		)

        _snake_case		:						List[Any]         =  ids_tensor([self.batch_size, self.seq_length, 4]  ,  self.range_bbox		)
        # Ensure that bbox is legal
        for i in range(bbox.shape[0]		):
              for j in range(bbox.shape[1]		):
                    if bbox[i, j, 3] < bbox[i, j, 1]:
                          _snake_case		:						List[str]         =  bbox[i, j, 3]
                          _snake_case		:						Tuple         =  bbox[i, j, 1]
                          _snake_case		:						Any         =  t
                    if bbox[i, j, 2] < bbox[i, j, 0]:
                          _snake_case		:						Optional[int]         =  bbox[i, j, 2]
                          _snake_case		:						Dict         =  bbox[i, j, 0]
                          _snake_case		:						Dict         =  t

        _snake_case		:						Optional[Any]         =  None
        if self.use_input_mask:
              _snake_case		:						Union[str, Any]         =  ids_tensor([self.batch_size, self.seq_length]  ,  vocab_size=2		)

        _snake_case		:						Optional[Any]         =  None
        if self.use_token_type_ids:
              _snake_case		:						str         =  ids_tensor([self.batch_size, self.seq_length]  ,  self.type_vocab_size		)

        _snake_case		:						Optional[Any]         =  None
        _snake_case		:						Optional[Any]         =  None
        _snake_case		:						List[str]         =  None
        if self.use_labels:
              _snake_case		:						Optional[int]         =  ids_tensor([self.batch_size]  ,  self.type_sequence_label_size		)
              _snake_case		:						int         =  ids_tensor([self.batch_size, self.seq_length]  ,  self.num_labels		)
              _snake_case		:						Optional[int]         =  ids_tensor([self.batch_size]  ,  self.num_choices		)

        _snake_case		:						List[Any]         =  self.get_config()

        return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        return LayoutLMConfig(
            vocab_size=self.vocab_size  ,  hidden_size=self.hidden_size  ,  num_hidden_layers=self.num_hidden_layers  ,  num_attention_heads=self.num_attention_heads  ,  intermediate_size=self.intermediate_size  ,  hidden_act=self.hidden_act  ,  hidden_dropout_prob=self.hidden_dropout_prob  ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,  max_position_embeddings=self.max_position_embeddings  ,  type_vocab_size=self.type_vocab_size  ,  initializer_range=self.initializer_range  ,  )







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    str:






        """simple docstring"""





        _snake_case		:						Optional[Any]         =  LayoutLMModel(config=lowercase__		)
        model.to(lowercase__		)
        model.eval()
        _snake_case		:						Tuple         =  model(lowercase__  ,  lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__		)
        _snake_case		:						Dict         =  model(lowercase__  ,  lowercase__  ,  token_type_ids=lowercase__		)
        _snake_case		:						Any         =  model(lowercase__  ,  lowercase__		)
        self.parent.assertEqual(result.last_hidden_state.shape  ,  (self.batch_size, self.seq_length, self.hidden_size)		)
        self.parent.assertEqual(result.pooler_output.shape  ,  (self.batch_size, self.hidden_size)		)







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






        """simple docstring"""





        _snake_case		:						Any         =  LayoutLMForMaskedLM(config=lowercase__		)
        model.to(lowercase__		)
        model.eval()
        _snake_case		:						int         =  model(lowercase__  ,  lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  labels=lowercase__		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.seq_length, self.vocab_size)		)







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






        """simple docstring"""





        _snake_case		:						Optional[int]         =  self.num_labels
        _snake_case		:						Tuple         =  LayoutLMForSequenceClassification(lowercase__		)
        model.to(lowercase__		)
        model.eval()
        _snake_case		:						str         =  model(
            lowercase__  ,  lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  labels=lowercase__		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.num_labels)		)







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    int:






        """simple docstring"""





        _snake_case		:						Union[str, Any]         =  self.num_labels
        _snake_case		:						Union[str, Any]         =  LayoutLMForTokenClassification(config=lowercase__		)
        model.to(lowercase__		)
        model.eval()
        _snake_case		:						Any         =  model(lowercase__  ,  lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  labels=lowercase__		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.seq_length, self.num_labels)		)







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    Any:






        """simple docstring"""





        _snake_case		:						List[str]         =  LayoutLMForQuestionAnswering(config=lowercase__		)
        model.to(lowercase__		)
        model.eval()
        _snake_case		:						int         =  model(
            lowercase__  ,  bbox=lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  start_positions=lowercase__  ,  end_positions=lowercase__  ,  )
        self.parent.assertEqual(result.start_logits.shape  ,  (self.batch_size, self.seq_length)		)
        self.parent.assertEqual(result.end_logits.shape  ,  (self.batch_size, self.seq_length)		)







  def 					UpperCAmelCase_					(		self		)		->    Optional[int]:






        """simple docstring"""





        _snake_case		:						int         =  self.prepare_config_and_inputs()
        (
            (
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				(
            _snake_case
        )  ,				
        )		:						List[str]         =  config_and_inputs
        _snake_case		:						Dict         =  {
            '''input_ids''': input_ids,
            '''bbox''': bbox,
            '''token_type_ids''': token_type_ids,
            '''attention_mask''': input_mask,
        }
        return config, inputs_dict





@require_torch
class lowerCamelCase    (a__    ,   a__    ,   unittest.TestCase       ):
  _lowercase	:						Optional[int]							       =					(
      (
          LayoutLMModel,
          LayoutLMForMaskedLM,
          LayoutLMForSequenceClassification,
          LayoutLMForTokenClassification,
          LayoutLMForQuestionAnswering,
      )
      if is_torch_available()
      else None
  )
  _lowercase	:						Any							       =					(
      {
          """document-question-answering""": LayoutLMForQuestionAnswering,
          """feature-extraction""": LayoutLMModel,
          """fill-mask""": LayoutLMForMaskedLM,
          """text-classification""": LayoutLMForSequenceClassification,
          """token-classification""": LayoutLMForTokenClassification,
          """zero-shot""": LayoutLMForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  _lowercase	:						Union[str, Any]							       =					True







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






        """simple docstring"""





        _snake_case		:						Dict         =  LayoutLMModelTester(self		)
        _snake_case		:						Union[str, Any]         =  ConfigTester(self  ,  config_class=lowercase__  ,  hidden_size=37		)







  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        self.config_tester.run_common_tests()







  def 					UpperCAmelCase_					(		self		)		->    Tuple:






        """simple docstring"""





        _snake_case		:						Dict         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__		)







  def 					UpperCAmelCase_					(		self		)		->    Dict:






        """simple docstring"""





        _snake_case		:						str         =  self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
              _snake_case		:						Dict         =  type
              self.model_tester.create_and_check_model(*lowercase__		)







  def 					UpperCAmelCase_					(		self		)		->    str:






        """simple docstring"""





        _snake_case		:						int         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*lowercase__		)







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






        """simple docstring"""





        _snake_case		:						Optional[Any]         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*lowercase__		)







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






        """simple docstring"""





        _snake_case		:						Tuple         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase__		)







  def 					UpperCAmelCase_					(		self		)		->    str:






        """simple docstring"""





        _snake_case		:						Dict         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowercase__		)







  @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''		)
  def 					UpperCAmelCase_					(		self		)		->    List[Any]:






        """simple docstring"""





        pass




def  _a     (				):





      """simple docstring"""



      _snake_case		:						str         =  torch.tensor([[101,1_019,1_014,1_016,1_037,12_849,4_747,1_004,14_246,2_278,5_439,4_524,5_002,2_930,2_193,2_930,4_341,3_208,1_005,1_055,2_171,2_848,11_300,3_531,102],[101,4_070,4_034,7_020,1_024,3_058,1_015,1_013,2_861,1_013,6_070,19_274,2_772,6_205,27_814,16_147,16_147,4_343,2_047,10_283,10_969,14_389,1_012,2_338,102]]      ,   device=lowerCAmelCase_						)  # noqa: E231
      _snake_case		:						str         =  torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],]      ,   device=lowerCAmelCase_						)  # noqa: E231
      _snake_case		:						Any         =  torch.tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1_000,1_000,1_000,1_000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1_000,1_000,1_000,1_000]]]      ,   device=lowerCAmelCase_						)  # noqa: E231
      _snake_case		:						Optional[int]         =  torch.tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]      ,   device=lowerCAmelCase_						)  # noqa: E231
      # these are sequence labels (i.e. at the token level)
      _snake_case		:						List[Any]         =  torch.tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]]      ,   device=lowerCAmelCase_						)  # noqa: E231
      # fmt: on

      return input_ids, attention_mask, bbox, token_type_ids, labels





@require_torch
class lowerCamelCase    (unittest.TestCase       ):







  @slow
  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        _snake_case		:						str         =  LayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased'''		).to(lowercase__		)

        _snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case		:						Optional[Any]         =  prepare_layoutlm_batch_inputs()

        # forward pass
        _snake_case		:						Any         =  model(input_ids=lowercase__  ,  bbox=lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__		)

        # test the sequence output on [0, :3, :3]
        _snake_case		:						List[str]         =  torch.tensor(
            [[0.1_785, -0.1_947, -0.0_425], [-0.3_254, -0.2_807, 0.2_553], [-0.5_391, -0.3_322, 0.3_364]]  ,  device=lowercase__  ,  )

        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]  ,  lowercase__  ,  atol=1E-3		)		)

        # test the pooled output on [1, :3]
        _snake_case		:						Optional[Any]         =  torch.tensor([-0.6_580, -0.0_214, 0.8_552]  ,  device=lowercase__		)

        self.assertTrue(torch.allclose(outputs.pooler_output[1, :3]  ,  lowercase__  ,  atol=1E-3		)		)







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Dict:






        """simple docstring"""





        _snake_case		:						Optional[Any]         =  LayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''  ,  num_labels=2		).to(
            lowercase__		)

        _snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case		:						Optional[int]         =  prepare_layoutlm_batch_inputs()

        # forward pass
        _snake_case		:						Optional[Any]         =  model(
            input_ids=lowercase__  ,  bbox=lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  labels=torch.tensor([1, 1]  ,  device=lowercase__		)  ,  )

        # test whether we get a loss as a scalar
        _snake_case		:						int         =  outputs.loss
        _snake_case		:						Tuple         =  torch.Size([]		)
        self.assertEqual(loss.shape  ,  lowercase__		)

        # test the shape of the logits
        _snake_case		:						Optional[int]         =  outputs.logits
        _snake_case		:						Optional[Any]         =  torch.Size((2, 2)		)
        self.assertEqual(logits.shape  ,  lowercase__		)







  @slow
  def 					UpperCAmelCase_					(		self		)		->    List[Any]:






        """simple docstring"""





        _snake_case		:						Tuple         =  LayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''  ,  num_labels=13		).to(
            lowercase__		)

        _snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case		:						Optional[int]         =  prepare_layoutlm_batch_inputs()

        # forward pass
        _snake_case		:						int         =  model(
            input_ids=lowercase__  ,  bbox=lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__  ,  labels=lowercase__		)

        # test the loss calculation to be around 2.65
        # expected_loss = torch.tensor(2.65, device=torch_device)

        # The loss is currently somewhat random and can vary between 0.1-0.3 atol.
        # self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=0.1))

        # test the shape of the logits
        _snake_case		:						List[str]         =  outputs.logits
        _snake_case		:						str         =  torch.Size((2, 25, 13)		)
        self.assertEqual(logits.shape  ,  lowercase__		)







  @slow
  def 					UpperCAmelCase_					(		self		)		->    str:






        """simple docstring"""





        _snake_case		:						List[Any]         =  LayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased'''		).to(lowercase__		)

        _snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case  ,				_snake_case		:						Optional[int]         =  prepare_layoutlm_batch_inputs()

        # forward pass
        _snake_case		:						Optional[int]         =  model(input_ids=lowercase__  ,  bbox=lowercase__  ,  attention_mask=lowercase__  ,  token_type_ids=lowercase__		)

        # test the shape of the logits
        _snake_case		:						Optional[int]         =  torch.Size((2, 25)		)
        self.assertEqual(outputs.start_logits.shape  ,  lowercase__		)
        self.assertEqual(outputs.end_logits.shape  ,  lowercase__		)









'''simple docstring'''

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
   from PIL import Image

   from transformers import ConvNextImageProcessor





class lowerCamelCase    :







  def __init__(		self  ,  lowercase__  ,  lowercase__=13  ,  lowercase__=32  ,  lowercase__=3  ,  lowercase__=4  ,  lowercase__=[10, 20, 30, 40]  ,  lowercase__=[2, 2, 3, 2]  ,  lowercase__=True  ,  lowercase__=True  ,  lowercase__=37  ,  lowercase__="gelu"  ,  lowercase__=10  ,  lowercase__=0.02  ,  lowercase__=3  ,  lowercase__=None  ,  )		->    Any:






        """simple docstring"""





        _snake_case		:						str         =  parent
        _snake_case		:						Any         =  batch_size
        _snake_case		:						Optional[Any]         =  image_size
        _snake_case		:						List[Any]         =  num_channels
        _snake_case		:						int         =  num_stages
        _snake_case		:						Any         =  hidden_sizes
        _snake_case		:						Dict         =  depths
        _snake_case		:						List[Any]         =  is_training
        _snake_case		:						Union[str, Any]         =  use_labels
        _snake_case		:						Dict         =  intermediate_size
        _snake_case		:						List[str]         =  hidden_act
        _snake_case		:						Optional[int]         =  type_sequence_label_size
        _snake_case		:						str         =  initializer_range
        _snake_case		:						Dict         =  scope







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






        """simple docstring"""





        _snake_case		:						Dict         =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        _snake_case		:						int         =  None
        if self.use_labels:
              _snake_case		:						Optional[int]         =  ids_tensor([self.batch_size]  ,  self.type_sequence_label_size		)

        _snake_case		:						Union[str, Any]         =  self.get_config()

        return config, pixel_values, labels







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






        """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=lowercase__  ,  initializer_range=self.initializer_range  ,  )







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    int:






        """simple docstring"""





        _snake_case		:						Tuple         =  TFConvNextModel(config=lowercase__		)
        _snake_case		:						Optional[int]         =  model(lowercase__  ,  training=lowercase__		)
        # 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 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    Optional[Any]:






        """simple docstring"""





        _snake_case		:						int         =  self.type_sequence_label_size
        _snake_case		:						Optional[int]         =  TFConvNextForImageClassification(lowercase__		)
        _snake_case		:						Dict         =  model(lowercase__  ,  labels=lowercase__  ,  training=lowercase__		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.type_sequence_label_size)		)







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






        """simple docstring"""





        _snake_case		:						Union[str, Any]         =  self.prepare_config_and_inputs()
        _snake_case  ,				_snake_case  ,				_snake_case		:						Union[str, Any]         =  config_and_inputs
        _snake_case		:						Optional[Any]         =  {'''pixel_values''': pixel_values}
        return config, inputs_dict





@require_tf
class lowerCamelCase    (a__    ,   a__    ,   unittest.TestCase       ):
  _lowercase	:						str							       =					(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
  _lowercase	:						List[str]							       =					(
      {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
      if is_tf_available()
      else {}
  )

  _lowercase	:						Optional[Any]							       =					False
  _lowercase	:						str							       =					False
  _lowercase	:						Tuple							       =					False
  _lowercase	:						Union[str, Any]							       =					False
  _lowercase	:						Dict							       =					False







  def 					UpperCAmelCase_					(		self		)		->    Any:






        """simple docstring"""





        _snake_case		:						List[str]         =  TFConvNextModelTester(self		)
        _snake_case		:						Tuple         =  ConfigTester(
            self  ,  config_class=lowercase__  ,  has_text_modality=lowercase__  ,  hidden_size=37  ,  )







  @unittest.skip(reason='''ConvNext does not use inputs_embeds'''		)
  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        pass







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''		)		) == 0  ,  reason='''TF does not support backprop for grouped convolutions on CPU.'''  ,  )
  @slow
  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        super().test_keras_fit()







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






        """simple docstring"""





        pass







  def 					UpperCAmelCase_					(		self		)		->    Any:






        """simple docstring"""





        _snake_case  ,				_snake_case		:						Dict         =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _snake_case		:						int         =  model_class(lowercase__		)
              _snake_case		:						Dict         =  inspect.signature(model.call		)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              _snake_case		:						Optional[int]         =  [*signature.parameters.keys()]

              _snake_case		:						int         =  ['''pixel_values''']
              self.assertListEqual(arg_names[:1]  ,  lowercase__		)







  def 					UpperCAmelCase_					(		self		)		->    str:






        """simple docstring"""





        _snake_case		:						Dict         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__		)







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''		)		) == 0  ,  reason='''TF does not support backprop for grouped convolutions on CPU.'''  ,  )
  def 					UpperCAmelCase_					(		self		)		->    Optional[Any]:






        """simple docstring"""





        super().test_dataset_conversion()







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






        """simple docstring"""





        def check_hidden_states_output(lowercase__  ,  lowercase__  ,  lowercase__		):
              _snake_case		:						List[Any]         =  model_class(lowercase__		)

              _snake_case		:						Dict         =  model(**self._prepare_for_class(lowercase__  ,  lowercase__		)		)
              _snake_case		:						str         =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _snake_case		:						List[Any]         =  self.model_tester.num_stages
              self.assertEqual(len(lowercase__		)  ,  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]  ,  )

        _snake_case  ,				_snake_case		:						Optional[Any]         =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _snake_case		:						int         =  True
              check_hidden_states_output(lowercase__  ,  lowercase__  ,  lowercase__		)

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

              check_hidden_states_output(lowercase__  ,  lowercase__  ,  lowercase__		)







  def 					UpperCAmelCase_					(		self		)		->    Any:






        """simple docstring"""





        _snake_case  ,				_snake_case		:						Dict         =  self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(lowercase__  ,  lowercase__  ,  lowercase__  ,  lowercase__={}		):
              _snake_case		:						Tuple         =  model(lowercase__  ,  return_dict=lowercase__  ,  **lowercase__		)
              _snake_case		:						Any         =  model(lowercase__  ,  return_dict=lowercase__  ,  **lowercase__		).to_tuple()

              def recursive_check(lowercase__  ,  lowercase__		):
                    if isinstance(lowercase__  ,  (List, Tuple)		):
                          for tuple_iterable_value, dict_iterable_value in zip(lowercase__  ,  lowercase__		):
                                recursive_check(lowercase__  ,  lowercase__		)
                    elif tuple_object is None:
                          return
                    else:
                          self.assertTrue(
                              all(tf.equal(lowercase__  ,  lowercase__		)		)  ,  msg=(
                                  '''Tuple and dict output are not equal. Difference:'''
                                  F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object		)		)}'''
                              )  ,  )

                    recursive_check(lowercase__  ,  lowercase__		)

        for model_class in self.all_model_classes:
              _snake_case		:						Dict         =  model_class(lowercase__		)

              _snake_case		:						Union[str, Any]         =  self._prepare_for_class(lowercase__  ,  lowercase__		)
              _snake_case		:						str         =  self._prepare_for_class(lowercase__  ,  lowercase__		)
              check_equivalence(lowercase__  ,  lowercase__  ,  lowercase__		)

              _snake_case		:						List[Any]         =  self._prepare_for_class(lowercase__  ,  lowercase__  ,  return_labels=lowercase__		)
              _snake_case		:						Any         =  self._prepare_for_class(lowercase__  ,  lowercase__  ,  return_labels=lowercase__		)
              check_equivalence(lowercase__  ,  lowercase__  ,  lowercase__		)

              _snake_case		:						List[str]         =  self._prepare_for_class(lowercase__  ,  lowercase__		)
              _snake_case		:						Union[str, Any]         =  self._prepare_for_class(lowercase__  ,  lowercase__		)
              check_equivalence(lowercase__  ,  lowercase__  ,  lowercase__  ,  {'''output_hidden_states''': True}		)

              _snake_case		:						Optional[int]         =  self._prepare_for_class(lowercase__  ,  lowercase__  ,  return_labels=lowercase__		)
              _snake_case		:						Any         =  self._prepare_for_class(lowercase__  ,  lowercase__  ,  return_labels=lowercase__		)
              check_equivalence(lowercase__  ,  lowercase__  ,  lowercase__  ,  {'''output_hidden_states''': True}		)







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






        """simple docstring"""





        _snake_case		:						str         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase__		)







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Optional[Any]:






        """simple docstring"""





        _snake_case		:						List[Any]         =  TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''		)
        self.assertIsNotNone(lowercase__		)




def  _a     (				):





      """simple docstring"""



      _snake_case		:						List[str]         =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
      return image





@require_tf
@require_vision
class lowerCamelCase    (unittest.TestCase       ):







  @cached_property
  def 					UpperCAmelCase_					(		self		)		->    Optional[int]:






        """simple docstring"""





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







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Any:






        """simple docstring"""





        _snake_case		:						Dict         =  TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		)

        _snake_case		:						str         =  self.default_image_processor
        _snake_case		:						Optional[int]         =  prepare_img()
        _snake_case		:						str         =  image_processor(images=lowercase__  ,  return_tensors='''tf'''		)

        # forward pass
        _snake_case		:						Union[str, Any]         =  model(**lowercase__		)

        # verify the logits
        _snake_case		:						Union[str, Any]         =  tf.TensorShape((1, 1_000)		)
        self.assertEqual(outputs.logits.shape  ,  lowercase__		)

        _snake_case		:						List[str]         =  tf.constant([-0.0_260, -0.4_739, 0.1_911]		)

        tf.debugging.assert_near(outputs.logits[0, :3]  ,  lowercase__  ,  atol=1E-4		)


