



'''simple docstring'''







import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
      from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import PoolFormerImageProcessor

class    lowerCamelCase_				(						lowerCAmelCase_	):






   '''simple docstring'''

   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      self.config_class(**self.inputs_dict			)
       self.parent.assertTrue(hasattr(__UpperCamelCase  ,    "hidden_sizes"			)			)
       self.parent.assertTrue(hasattr(__UpperCamelCase  ,    "num_encoder_blocks"			)			)

class    lowerCamelCase_				:






   '''simple docstring'''

   def __init__(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=13  ,    __UpperCamelCase=64  ,    __UpperCamelCase=3  ,    __UpperCamelCase=4  ,    __UpperCamelCase=[2, 2, 2, 2]  ,    __UpperCamelCase=[8, 4, 2, 1]  ,    __UpperCamelCase=[16, 32, 64, 1_28]  ,    __UpperCamelCase=[1, 4, 8, 16]  ,    __UpperCamelCase=False  ,    __UpperCamelCase=True  ,    __UpperCamelCase="gelu"  ,    __UpperCamelCase=0.1  ,    __UpperCamelCase=0.02  ,    __UpperCamelCase=3  ,    __UpperCamelCase=None  ,    ):
       UpperCamelCase__	     =      parent
       UpperCamelCase__	     =      batch_size
       UpperCamelCase__	     =      image_size
       UpperCamelCase__	     =      num_channels
       UpperCamelCase__	     =      num_encoder_blocks
       UpperCamelCase__	     =      sr_ratios
       UpperCamelCase__	     =      depths
       UpperCamelCase__	     =      hidden_sizes
       UpperCamelCase__	     =      downsampling_rates
       UpperCamelCase__	     =      is_training
       UpperCamelCase__	     =      use_labels
       UpperCamelCase__	     =      hidden_act
       UpperCamelCase__	     =      hidden_dropout_prob
       UpperCamelCase__	     =      initializer_range
       UpperCamelCase__	     =      num_labels
       UpperCamelCase__	     =      scope


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

       UpperCamelCase__	     =      PoolFormerConfig(
           image_size=self.image_size  ,    num_channels=self.num_channels  ,    num_encoder_blocks=self.num_encoder_blocks  ,    depths=self.depths  ,    hidden_sizes=self.hidden_sizes  ,    hidden_act=self.hidden_act  ,    hidden_dropout_prob=self.hidden_dropout_prob  ,    initializer_range=self.initializer_range  ,    )

       return config, pixel_values, labels


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			):
       UpperCamelCase__	     =      PoolFormerModel(config=__UpperCamelCase			)
       model.to(__UpperCamelCase			)
       model.eval()
       UpperCamelCase__	     =      model(__UpperCamelCase			)
       UpperCamelCase__	     =      UpperCamelCase__	     =      self.image_size // 32.0
       self.parent.assertEqual(
           result.last_hidden_state.shape  ,    (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)			)







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

@require_torch
class    lowerCamelCase_				(						lowerCAmelCase_       ,     lowerCAmelCase_       ,     unittest.TestCase	):






   '''simple docstring'''

   A			:  int					=						(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
   A			:  List[str]					=						(
       {"feature-extraction": PoolFormerModel, "image-classification": PoolFormerForImageClassification}
       if is_torch_available()
       else {}
   )

   A			:  int					=						False
   A			:  Tuple					=						False
   A			:  str					=						False
   A			:  Optional[int]					=						False
   A			:  List[Any]					=						False


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      PoolFormerModelTester(self			)
       UpperCamelCase__	     =      PoolFormerConfigTester(self  ,    config_class=__UpperCamelCase			)


   def 						_UpperCamelCase							(	self			):
       self.config_tester.run_common_tests()


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__UpperCamelCase			)


   @unittest.skip("PoolFormer does not use inputs_embeds"			)
   def 						_UpperCamelCase							(	self			):
       pass


   @unittest.skip("PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"			)
   def 						_UpperCamelCase							(	self			):
       pass


   def 						_UpperCamelCase							(	self			):
       def check_hidden_states_output(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			):
           UpperCamelCase__	     =      model_class(__UpperCamelCase			)
           model.to(__UpperCamelCase			)
           model.eval()

           with torch.no_grad():
               UpperCamelCase__	     =      model(**self._prepare_for_class(__UpperCamelCase  ,    __UpperCamelCase			)			)

           UpperCamelCase__	     =      outputs.hidden_states

           UpperCamelCase__	     =      self.model_tester.num_encoder_blocks
           self.assertEqual(len(__UpperCamelCase			)  ,    __UpperCamelCase			)

           # verify the first hidden states (first block)
           self.assertListEqual(
               list(hidden_states[0].shape[-3:]			)  ,    [
                   self.model_tester.hidden_sizes[0],
                   self.model_tester.image_size // 4,
                   self.model_tester.image_size // 4,
               ]  ,    )

       UpperCamelCase__     ,	UpperCamelCase__	     =      self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__	     =      True
           check_hidden_states_output(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			)

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

           check_hidden_states_output(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			)


   def 						_UpperCamelCase							(	self			):
       if not self.model_tester.is_training:
           return

       UpperCamelCase__     ,	UpperCamelCase__	     =      self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__	     =      True

       for model_class in self.all_model_classes:
           if model_class in get_values(__UpperCamelCase			):
               continue
           UpperCamelCase__	     =      model_class(__UpperCamelCase			)
           model.to(__UpperCamelCase			)
           model.train()
           UpperCamelCase__	     =      self._prepare_for_class(__UpperCamelCase  ,    __UpperCamelCase  ,    return_labels=__UpperCamelCase			)
           UpperCamelCase__	     =      model(**__UpperCamelCase			).loss
           loss.backward()


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__     ,	UpperCamelCase__	     =      self.model_tester.prepare_config_and_inputs_for_common()

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

           UpperCamelCase__	     =      ["pixel_values"]
           self.assertListEqual(arg_names[:1]  ,    __UpperCamelCase			)







   @slow
   def 						_UpperCamelCase							(	self			):
       for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__	     =      PoolFormerModel.from_pretrained(__UpperCamelCase			)
           self.assertIsNotNone(__UpperCamelCase			)





def     snake_case__			():
    UpperCamelCase__	     =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
    return image





@require_torch
class    lowerCamelCase_				(						unittest.TestCase	):






   '''simple docstring'''

   @slow
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      PoolFormerImageProcessor()
       UpperCamelCase__	     =      PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"			).to(__UpperCamelCase			)

       UpperCamelCase__	     =      image_processor(images=prepare_img()  ,    return_tensors="pt"			).to(__UpperCamelCase			)

       # forward pass
       with torch.no_grad():
           UpperCamelCase__	     =      model(**__UpperCamelCase			)

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

       UpperCamelCase__	     =      torch.tensor([-0.6_113, 0.1_685, -0.0_492]			).to(__UpperCamelCase			)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,    __UpperCamelCase  ,    atol=1e-4			)			)









'''simple docstring'''







import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


lowercase__  :	str            =      logging.get_logger(__name__)

@dataclass
class    lowerCamelCase_				:






   '''simple docstring'''

   A			:  str
   A			:  str
   A			:  Optional[str]					=						None
   A			:  Optional[str]					=						None


   def 						_UpperCamelCase							(	self			):
       return json.dumps(dataclasses.asdict(self			)  ,    indent=2			) + "\n"

@dataclass(frozen=lowerCAmelCase_	)
class    lowerCamelCase_				:






   '''simple docstring'''

   A			:  List[int]
   A			:  Optional[List[int]]					=						None
   A			:  Optional[List[int]]					=						None
   A			:  Optional[Union[int, float]]					=						None


   def 						_UpperCamelCase							(	self			):
       return json.dumps(dataclasses.asdict(self			)			) + "\n"

class    lowerCamelCase_				:






   '''simple docstring'''

   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       if len(self.get_labels()			) > 1:
           UpperCamelCase__	     =      self.get_labels()[int(example.label			)]
       return example







   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=None			):
       with open(__UpperCamelCase  ,    "r"  ,    encoding="utf-8-sig"			) as f:
           return list(csv.reader(__UpperCamelCase  ,    delimiter="\t"  ,    quotechar=__UpperCamelCase			)			)

class    lowerCamelCase_				(						lowerCAmelCase_	):






   '''simple docstring'''

   def __init__(	self  ,    __UpperCamelCase=None  ,    __UpperCamelCase=None  ,    __UpperCamelCase="classification"  ,    __UpperCamelCase=False			):
       UpperCamelCase__	     =      [] if labels is None else labels
       UpperCamelCase__	     =      [] if examples is None else examples
       UpperCamelCase__	     =      mode
       UpperCamelCase__	     =      verbose


   def __len__(	self			):
       return len(self.examples			)


   def __getitem__(	self  ,    __UpperCamelCase			):
       if isinstance(__UpperCamelCase  ,    __UpperCamelCase			):
           return SingleSentenceClassificationProcessor(labels=self.labels  ,    examples=self.examples[idx]			)
       return self.examples[idx]


   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=""  ,    __UpperCamelCase=0  ,    __UpperCamelCase=1  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    **__UpperCamelCase			):
       UpperCamelCase__	     =      cls(**__UpperCamelCase			)
       processor.add_examples_from_csv(
           __UpperCamelCase  ,    split_name=__UpperCamelCase  ,    column_label=__UpperCamelCase  ,    column_text=__UpperCamelCase  ,    column_id=__UpperCamelCase  ,    skip_first_row=__UpperCamelCase  ,    overwrite_labels=__UpperCamelCase  ,    overwrite_examples=__UpperCamelCase  ,    )
       return processor


   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    **__UpperCamelCase			):
       UpperCamelCase__	     =      cls(**__UpperCamelCase			)
       processor.add_examples(__UpperCamelCase  ,    labels=__UpperCamelCase			)
       return processor


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=""  ,    __UpperCamelCase=0  ,    __UpperCamelCase=1  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False  ,    ):
       UpperCamelCase__	     =      self._read_tsv(__UpperCamelCase			)
       if skip_first_row:
           UpperCamelCase__	     =      lines[1:]
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      []
       for i, line in enumerate(__UpperCamelCase			):
           texts.append(line[column_text]			)
           labels.append(line[column_label]			)
           if column_id is not None:
               ids.append(line[column_id]			)
           else:
               UpperCamelCase__	     =      f'{split_name}-{i}' if split_name else str(__UpperCamelCase			)
               ids.append(__UpperCamelCase			)

       return self.add_examples(
           __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    overwrite_labels=__UpperCamelCase  ,    overwrite_examples=__UpperCamelCase			)


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False			):
       if labels is not None and len(__UpperCamelCase			) != len(__UpperCamelCase			):
           raise ValueError(
               f'Text and labels have mismatched lengths {len(__UpperCamelCase			)} and {len(__UpperCamelCase			)}'			)
       if ids is not None and len(__UpperCamelCase			) != len(__UpperCamelCase			):
           raise ValueError(f'Text and ids have mismatched lengths {len(__UpperCamelCase			)} and {len(__UpperCamelCase			)}'			)
       if ids is None:
           UpperCamelCase__	     =      [None] * len(__UpperCamelCase			)
       if labels is None:
           UpperCamelCase__	     =      [None] * len(__UpperCamelCase			)
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      set()
       for text_or_text_and_label, label, guid in zip(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			):
           if isinstance(__UpperCamelCase  ,    (tuple, list)			) and label is None:
               UpperCamelCase__     ,	UpperCamelCase__	     =      text_or_text_and_label
           else:
               UpperCamelCase__	     =      text_or_text_and_label
           added_labels.add(__UpperCamelCase			)
           examples.append(InputExample(guid=__UpperCamelCase  ,    text_a=__UpperCamelCase  ,    text_b=__UpperCamelCase  ,    label=__UpperCamelCase			)			)

       # Update examples
       if overwrite_examples:
           UpperCamelCase__	     =      examples
       else:
           self.examples.extend(__UpperCamelCase			)

       # Update labels
       if overwrite_labels:
           UpperCamelCase__	     =      list(__UpperCamelCase			)
       else:
           UpperCamelCase__	     =      list(set(self.labels			).union(__UpperCamelCase			)			)

       return self.examples







   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=0  ,    __UpperCamelCase=True  ,    __UpperCamelCase=None  ,    ):
       if max_length is None:
           UpperCamelCase__	     =      tokenizer.max_len

       UpperCamelCase__	     =      {label: i for i, label in enumerate(self.labels			)}

       UpperCamelCase__	     =      []
       for ex_index, example in enumerate(self.examples			):
           if ex_index % 1_00_00 == 0:
               logger.info(f'Tokenizing example {ex_index}'			)

           UpperCamelCase__	     =      tokenizer.encode(
               example.text_a  ,    add_special_tokens=__UpperCamelCase  ,    max_length=min(__UpperCamelCase  ,    tokenizer.max_len			)  ,    )
           all_input_ids.append(__UpperCamelCase			)

       UpperCamelCase__	     =      max(len(__UpperCamelCase			) for input_ids in all_input_ids			)

       UpperCamelCase__	     =      []
       for ex_index, (input_ids, example) in enumerate(zip(__UpperCamelCase  ,    self.examples			)			):
           if ex_index % 1_00_00 == 0:
               logger.info(f'Writing example {ex_index}/{len(self.examples			)}'			)
           # The mask has 1 for real tokens and 0 for padding tokens. Only real
           # tokens are attended to.
           UpperCamelCase__	     =      [1 if mask_padding_with_zero else 0] * len(__UpperCamelCase			)

           # Zero-pad up to the sequence length.
           UpperCamelCase__	     =      batch_length - len(__UpperCamelCase			)
           if pad_on_left:
               UpperCamelCase__	     =      ([pad_token] * padding_length) + input_ids
               UpperCamelCase__	     =      ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
           else:
               UpperCamelCase__	     =      input_ids + ([pad_token] * padding_length)
               UpperCamelCase__	     =      attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

           if len(__UpperCamelCase			) != batch_length:
               raise ValueError(f'Error with input length {len(__UpperCamelCase			)} vs {batch_length}'			)
           if len(__UpperCamelCase			) != batch_length:
               raise ValueError(f'Error with input length {len(__UpperCamelCase			)} vs {batch_length}'			)

           if self.mode == "classification":
               UpperCamelCase__	     =      label_map[example.label]
           elif self.mode == "regression":
               UpperCamelCase__	     =      float(example.label			)
           else:
               raise ValueError(self.mode			)

           if ex_index < 5 and self.verbose:
               logger.info("*** Example ***"			)
               logger.info(f'guid: {example.guid}'			)
               logger.info(f'input_ids: {" ".join([str(__UpperCamelCase			) for x in input_ids]			)}'			)
               logger.info(f'attention_mask: {" ".join([str(__UpperCamelCase			) for x in attention_mask]			)}'			)
               logger.info(f'label: {example.label} (id = {label})'			)

           features.append(InputFeatures(input_ids=__UpperCamelCase  ,    attention_mask=__UpperCamelCase  ,    label=__UpperCamelCase			)			)

       if return_tensors is None:
           return features
       elif return_tensors == "tf":
           if not is_tf_available():
               raise RuntimeError("return_tensors set to 'tf' but TensorFlow 2.0 can't be imported"			)
           import tensorflow as tf

           def gen():
               for ex in features:
                   yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

           UpperCamelCase__	     =      tf.data.Dataset.from_generator(
               __UpperCamelCase  ,    ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa)  ,    ({"input_ids": tf.TensorShape([None]			), "attention_mask": tf.TensorShape([None]			)}, tf.TensorShape([]			))  ,    )
           return dataset
       elif return_tensors == "pt":
           if not is_torch_available():
               raise RuntimeError("return_tensors set to 'pt' but PyTorch can't be imported"			)
           import torch
           from torch.utils.data import TensorDataset

           UpperCamelCase__	     =      torch.tensor([f.input_ids for f in features]  ,    dtype=torch.long			)
           UpperCamelCase__	     =      torch.tensor([f.attention_mask for f in features]  ,    dtype=torch.long			)
           if self.mode == "classification":
               UpperCamelCase__	     =      torch.tensor([f.label for f in features]  ,    dtype=torch.long			)
           elif self.mode == "regression":
               UpperCamelCase__	     =      torch.tensor([f.label for f in features]  ,    dtype=torch.float			)

           UpperCamelCase__	     =      TensorDataset(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			)
           return dataset
       else:
           raise ValueError("return_tensors should be one of 'tf' or 'pt'"			)




