

"""simple docstring"""





import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
   import faiss




@require_faiss
class 					_lowerCAmelCase  (	lowercase   ):







 """simple docstring"""







 def 					_lowercase (			self							:			str	):
    __lowercase								=						tempfile.mkdtemp()
    __lowercase								=						8

    # DPR tok
    __lowercase								=						[
        "[UNK]",
        "[CLS]",
        "[SEP]",
        "[PAD]",
        "[MASK]",
        "want",
        "##want",
        "##ed",
        "wa",
        "un",
        "runn",
        "##ing",
        ",",
        "low",
        "lowest",
    ]
    __lowercase								=						os.path.join(self.tmpdirname,					"dpr_tokenizer"	)
    os.makedirs(UpperCAmelCase__,					exist_ok=UpperCAmelCase__	)
    __lowercase								=						os.path.join(UpperCAmelCase__,					DPR_VOCAB_FILES_NAMES["vocab_file"]	)
    with open(self.vocab_file,					"w",					encoding="utf-8"	) as vocab_writer:
       vocab_writer.write("".join([x + "\n" for x in vocab_tokens]	)	)

    # BART tok
    __lowercase								=						[
        "l",
        "o",
        "w",
        "e",
        "r",
        "s",
        "t",
        "i",
        "d",
        "n",
        "\u0120",
        "\u0120l",
        "\u0120n",
        "\u0120lo",
        "\u0120low",
        "er",
        "\u0120lowest",
        "\u0120newer",
        "\u0120wider",
        "<unk>",
    ]
    __lowercase								=						dict(zip(UpperCAmelCase__,					range(len(UpperCAmelCase__	)	)	)	)
    __lowercase								=						["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
    __lowercase								=						{"unk_token": "<unk>"}

    __lowercase								=						os.path.join(self.tmpdirname,					"bart_tokenizer"	)
    os.makedirs(UpperCAmelCase__,					exist_ok=UpperCAmelCase__	)
    __lowercase								=						os.path.join(UpperCAmelCase__,					BART_VOCAB_FILES_NAMES["vocab_file"]	)
    __lowercase								=						os.path.join(UpperCAmelCase__,					BART_VOCAB_FILES_NAMES["merges_file"]	)
    with open(self.vocab_file,					"w",					encoding="utf-8"	) as fp:
       fp.write(json.dumps(UpperCAmelCase__	) + "\n"	)
    with open(self.merges_file,					"w",					encoding="utf-8"	) as fp:
       fp.write("\n".join(UpperCAmelCase__	)	)


 def 					_lowercase (			self							:			List[str]	):
    return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname,					"dpr_tokenizer"	)	)


 def 					_lowercase (			self							:			Tuple	):
    return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname,					"dpr_tokenizer"	)	)


 def 					_lowercase (			self							:			Union[str, Any]	):
    return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname,					"bart_tokenizer"	)	)


 def 					_lowercase (			self							:			Any	):
    shutil.rmtree(self.tmpdirname	)


 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						Dataset.from_dict(
        {
            "id": ["0", "1"],
            "text": ["foo", "bar"],
            "title": ["Foo", "Bar"],
            "embeddings": [np.ones(self.retrieval_vector_size	), 2 * np.ones(self.retrieval_vector_size	)],
        }	)
    dataset.add_faiss_index("embeddings",					string_factory="Flat",					metric_type=faiss.METRIC_INNER_PRODUCT	)
    return dataset


 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						self.get_dummy_dataset()
    __lowercase								=						RagConfig(
        retrieval_vector_size=self.retrieval_vector_size,					question_encoder=DPRConfig().to_dict(),					generator=BartConfig().to_dict(),					)
    with patch("transformers.models.rag.retrieval_rag.load_dataset"	) as mock_load_dataset:
       __lowercase								=						dataset
       __lowercase								=						RagRetriever(
           UpperCAmelCase__,					question_encoder_tokenizer=self.get_dpr_tokenizer(),					generator_tokenizer=self.get_bart_tokenizer(),					)
    return retriever


 def 					_lowercase (			self							:			List[str],					UpperCAmelCase__							:			bool	):
    __lowercase								=						self.get_dummy_dataset()
    __lowercase								=						RagConfig(
        retrieval_vector_size=self.retrieval_vector_size,					question_encoder=DPRConfig().to_dict(),					generator=BartConfig().to_dict(),					index_name="custom",					)
    if from_disk:
       __lowercase								=						os.path.join(self.tmpdirname,					"dataset"	)
       __lowercase								=						os.path.join(self.tmpdirname,					"index.faiss"	)
       dataset.get_index("embeddings"	).save(os.path.join(self.tmpdirname,					"index.faiss"	)	)
       dataset.drop_index("embeddings"	)
       dataset.save_to_disk(os.path.join(self.tmpdirname,					"dataset"	)	)
       del dataset
       __lowercase								=						RagRetriever(
           UpperCAmelCase__,					question_encoder_tokenizer=self.get_dpr_tokenizer(),					generator_tokenizer=self.get_bart_tokenizer(),					)
    else:
       __lowercase								=						RagRetriever(
           UpperCAmelCase__,					question_encoder_tokenizer=self.get_dpr_tokenizer(),					generator_tokenizer=self.get_bart_tokenizer(),					index=CustomHFIndex(config.retrieval_vector_size,					UpperCAmelCase__	),					)
    return retriever


 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						Dataset.from_dict(
        {
            "id": ["0", "1"],
            "text": ["foo", "bar"],
            "title": ["Foo", "Bar"],
            "embeddings": [np.ones(self.retrieval_vector_size + 1	), 2 * np.ones(self.retrieval_vector_size + 1	)],
        }	)
    dataset.add_faiss_index("embeddings",					string_factory="Flat",					metric_type=faiss.METRIC_INNER_PRODUCT	)

    __lowercase								=						os.path.join(self.tmpdirname,					"hf_bert_base.hnswSQ8_correct_phi_128.c_index"	)
    dataset.save_faiss_index("embeddings",					index_file_name + ".index.dpr"	)
    pickle.dump(dataset["id"],					open(index_file_name + ".index_meta.dpr",					"wb"	)	)

    __lowercase								=						os.path.join(self.tmpdirname,					"psgs_w100.tsv.pkl"	)
    __lowercase								=						{sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
    pickle.dump(UpperCAmelCase__,					open(UpperCAmelCase__,					"wb"	)	)

    __lowercase								=						RagConfig(
        retrieval_vector_size=self.retrieval_vector_size,					question_encoder=DPRConfig().to_dict(),					generator=BartConfig().to_dict(),					index_name="legacy",					index_path=self.tmpdirname,					)
    __lowercase								=						RagRetriever(
        UpperCAmelCase__,					question_encoder_tokenizer=self.get_dpr_tokenizer(),					generator_tokenizer=self.get_bart_tokenizer()	)
    return retriever


 def 					_lowercase (			self							:			List[str]	):
    __lowercase								=						1
    __lowercase								=						self.get_dummy_canonical_hf_index_retriever()
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase		,__lowercase		,__lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=UpperCAmelCase__	)
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertEqual(len(UpperCAmelCase__	),					2	)
    self.assertEqual(sorted(doc_dicts[0]	),					["embeddings", "id", "text", "title"]	)
    self.assertEqual(len(doc_dicts[0]["id"]	),					UpperCAmelCase__	)
    self.assertEqual(doc_dicts[0]["id"][0],					"1"	)  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]["id"][0],					"0"	)  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist(),					[[1], [0]]	)


 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						self.get_dummy_canonical_hf_index_retriever()
    with tempfile.TemporaryDirectory() as tmp_dirname:
       with patch("transformers.models.rag.retrieval_rag.load_dataset"	) as mock_load_dataset:
          __lowercase								=						self.get_dummy_dataset()
          retriever.save_pretrained(UpperCAmelCase__	)
          __lowercase								=						RagRetriever.from_pretrained(UpperCAmelCase__	)
          self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
          __lowercase								=						np.array(
              [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
          __lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=1	)
          self.assertTrue(out is not None	)


 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						1
    __lowercase								=						self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__	)
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase		,__lowercase		,__lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=UpperCAmelCase__	)
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertEqual(len(UpperCAmelCase__	),					2	)
    self.assertEqual(sorted(doc_dicts[0]	),					["embeddings", "id", "text", "title"]	)
    self.assertEqual(len(doc_dicts[0]["id"]	),					UpperCAmelCase__	)
    self.assertEqual(doc_dicts[0]["id"][0],					"1"	)  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]["id"][0],					"0"	)  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist(),					[[1], [0]]	)


 def 					_lowercase (			self							:			str	):
    __lowercase								=						self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__	)
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(UpperCAmelCase__	)
       __lowercase								=						RagRetriever.from_pretrained(UpperCAmelCase__	)
       self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
       __lowercase								=						np.array(
           [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
       __lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=1	)
       self.assertTrue(out is not None	)


 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						1
    __lowercase								=						self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__	)
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase		,__lowercase		,__lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=UpperCAmelCase__	)
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertEqual(len(UpperCAmelCase__	),					2	)
    self.assertEqual(sorted(doc_dicts[0]	),					["embeddings", "id", "text", "title"]	)
    self.assertEqual(len(doc_dicts[0]["id"]	),					UpperCAmelCase__	)
    self.assertEqual(doc_dicts[0]["id"][0],					"1"	)  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]["id"][0],					"0"	)  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist(),					[[1], [0]]	)


 def 					_lowercase (			self							:			Any	):
    __lowercase								=						self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__	)
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(UpperCAmelCase__	)
       __lowercase								=						RagRetriever.from_pretrained(UpperCAmelCase__	)
       self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
       __lowercase								=						np.array(
           [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
       __lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=1	)
       self.assertTrue(out is not None	)


 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						1
    __lowercase								=						self.get_dummy_legacy_index_retriever()
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase		,__lowercase		,__lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=UpperCAmelCase__	)
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertEqual(len(UpperCAmelCase__	),					2	)
    self.assertEqual(sorted(doc_dicts[0]	),					["text", "title"]	)
    self.assertEqual(len(doc_dicts[0]["text"]	),					UpperCAmelCase__	)
    self.assertEqual(doc_dicts[0]["text"][0],					"bar"	)  # max inner product is reached with second doc
    self.assertEqual(doc_dicts[1]["text"][0],					"foo"	)  # max inner product is reached with first doc
    self.assertListEqual(doc_ids.tolist(),					[[1], [0]]	)


 def 					_lowercase (			self							:			Optional[Any]	):
    __lowercase								=						self.get_dummy_legacy_index_retriever()
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(UpperCAmelCase__	)
       __lowercase								=						RagRetriever.from_pretrained(UpperCAmelCase__	)
       self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
       __lowercase								=						np.array(
           [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
       __lowercase								=						retriever.retrieve(UpperCAmelCase__,					n_docs=1	)
       self.assertTrue(out is not None	)


 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def 					_lowercase (			self							:			Tuple	):
    import torch

    __lowercase								=						1
    __lowercase								=						self.get_dummy_canonical_hf_index_retriever()
    __lowercase								=						[[5, 7], [1_0, 1_1]]
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase								=						retriever(UpperCAmelCase__,					UpperCAmelCase__,					prefix=retriever.config.generator.prefix,					n_docs=UpperCAmelCase__	)
    __lowercase		,__lowercase		,__lowercase								=						(
        out["context_input_ids"],
        out["context_attention_mask"],
        out["retrieved_doc_embeds"],
    )
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
    self.assertIsInstance(UpperCAmelCase__,					UpperCAmelCase__	)
    self.assertIsInstance(UpperCAmelCase__,					np.ndarray	)

    __lowercase								=						retriever(
        UpperCAmelCase__,					UpperCAmelCase__,					prefix=retriever.config.generator.prefix,					n_docs=UpperCAmelCase__,					return_tensors="pt",					)
    __lowercase		,__lowercase		,__lowercase		,__lowercase								=						(  # noqa: F841
        out["context_input_ids"],
        out["context_attention_mask"],
        out["retrieved_doc_embeds"],
        out["doc_ids"],
    )
    self.assertEqual(retrieved_doc_embeds.shape,					(2, n_docs, self.retrieval_vector_size)	)
    self.assertIsInstance(UpperCAmelCase__,					torch.Tensor	)
    self.assertIsInstance(UpperCAmelCase__,					torch.Tensor	)
    self.assertIsInstance(UpperCAmelCase__,					torch.Tensor	)



 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def 					_lowercase (			self							:			Any	):
    __lowercase								=						self.get_dpr_ctx_encoder_tokenizer()
    __lowercase								=						1
    __lowercase								=						self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__	)
    retriever.set_ctx_encoder_tokenizer(UpperCAmelCase__	)

    __lowercase								=						[[5, 7], [1_0, 1_1]]
    __lowercase								=						np.array(
        [np.ones(self.retrieval_vector_size	), -np.ones(self.retrieval_vector_size	)],					dtype=np.floataa	)
    __lowercase								=						retriever(UpperCAmelCase__,					UpperCAmelCase__,					prefix=retriever.config.generator.prefix,					n_docs=UpperCAmelCase__	)

    self.assertEqual(
        len(UpperCAmelCase__	),					6	)  # check whether the retriever output consist of 6 attributes including tokenized docs
    self.assertEqual(
        all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask")	),					UpperCAmelCase__	)  # check for doc token related keys in dictionary.









"""simple docstring"""







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class       UpperCamelCase__   :




      """simple docstring"""




      def __init__(      self				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      str    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=3    ,			SCREAMING_SNAKE_CASE_				:      Any=3_2    ,			SCREAMING_SNAKE_CASE_				:      int=3    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=1_0    ,			SCREAMING_SNAKE_CASE_				:      Dict=[1_0, 2_0, 3_0, 4_0]    ,			SCREAMING_SNAKE_CASE_				:      int=[1, 1, 2, 1]    ,			SCREAMING_SNAKE_CASE_				:      int=True    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]=True    ,			SCREAMING_SNAKE_CASE_				:      int="relu"    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3    ,			SCREAMING_SNAKE_CASE_				:      List[str]=None    ,			):
        lowerCAmelCase_   :				Optional[int]								= parent
        lowerCAmelCase_   :				Union[str, Any]								= batch_size
        lowerCAmelCase_   :				Optional[int]								= image_size
        lowerCAmelCase_   :				Optional[int]								= num_channels
        lowerCAmelCase_   :				Any								= embeddings_size
        lowerCAmelCase_   :				Dict								= hidden_sizes
        lowerCAmelCase_   :				Any								= depths
        lowerCAmelCase_   :				Optional[int]								= is_training
        lowerCAmelCase_   :				int								= use_labels
        lowerCAmelCase_   :				List[Any]								= hidden_act
        lowerCAmelCase_   :				Dict								= num_labels
        lowerCAmelCase_   :				Optional[int]								= scope
        lowerCAmelCase_   :				Tuple								= len(SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				List[str]								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

        lowerCAmelCase_   :				List[str]								= self.get_config()
        return config, pixel_values, labels



      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        return RegNetConfig(
            num_channels=self.num_channels    ,			embeddings_size=self.embeddings_size    ,			hidden_sizes=self.hidden_sizes    ,			depths=self.depths    ,			hidden_act=self.hidden_act    ,			num_labels=self.num_labels    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any    ,			SCREAMING_SNAKE_CASE_				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      int       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModel(config=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			training=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 // 3_2, self.image_size // 3_2)    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]       ):
        lowerCAmelCase_   :				int								= self.num_labels
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification(SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Dict								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)       )





      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				str								= self.prepare_config_and_inputs()
        lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				Tuple								= config_and_inputs
        lowerCAmelCase_   :				Optional[Any]								= {'pixel_values': pixel_values}
        return config, inputs_dict







@require_tf
class       UpperCamelCase__   (	lowercase_,					lowercase_,					unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      _SCREAMING_SNAKE_CASE  				=     (
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModelTester(self       )
        lowerCAmelCase_   :				Tuple								= ConfigTester(self    ,			config_class=SCREAMING_SNAKE_CASE_    ,			has_text_modality=SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        return



      @unittest.skip(reason='RegNet does not use inputs_embeds'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        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      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        super().test_keras_fit()



      @unittest.skip(reason='RegNet does not support input and output embeddings'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        pass



      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				Optional[int]								= self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase_   :				Any								= ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Dict								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      Tuple       ):
          lowerCAmelCase_   :				List[Any]								= model_class(SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )    ,			training=SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[str]								= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowerCAmelCase_   :				Union[str, Any]								= self.model_tester.num_stages
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			expected_num_stages + 1       )

          # RegNet'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 // 2, self.model_tester.image_size // 2]    ,			)

        lowerCAmelCase_						,lowerCAmelCase_   :				List[Any]								= self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase_   :				Optional[int]								= ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            lowerCAmelCase_   :				str								= layer_type
            lowerCAmelCase_   :				List[str]								= 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_   :				List[str]								= True

            check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				int								= self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      str    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      str={}       ):
          lowerCAmelCase_   :				Optional[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       ).to_tuple()

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

            recursive_check(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				Union[str, Any]								= model_class(SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Optional[int]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				str								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Tuple								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				int								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Any								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        lowerCAmelCase_   :				List[str]								= 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				:      Union[str, Any]       ):
        for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_   :				int								= TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )




def 				UpperCamelCase_    (    )						->   List[str]:

  """simple docstring"""




  lowerCAmelCase_   :				Optional[Any]								= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







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




      """simple docstring"""




      @cached_property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        return (
            AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
            if is_vision_available()
            else None
        )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

        lowerCAmelCase_   :				Tuple								= self.default_image_processor
        lowerCAmelCase_   :				Dict								= prepare_img()
        lowerCAmelCase_   :				Union[str, Any]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='tf'       )

        # forward pass
        lowerCAmelCase_   :				List[str]								= model(**SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )

        # verify the logits
        lowerCAmelCase_   :				Optional[Any]								= tf.TensorShape((1, 1_0_0_0)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[Any]								= tf.constant([-0.41_80, -1.50_51, -3.48_36]       )

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





