



"""simple docstring"""

import inspect
import unittest

from transformers import BitConfig
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 torch import nn

       from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel
       from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image




class  _UpperCAmelCase :

 def __init__(  self	: Tuple						,  lowercase_	: Optional[int]						,  lowercase_	: str=3						,  lowercase_	: Optional[int]=32						,  lowercase_	: Dict=3						,  lowercase_	: Dict=10						,  lowercase_	: Tuple=[8, 16, 32, 64]						,  lowercase_	: int=[1, 1, 2, 1]						,  lowercase_	: Union[str, Any]=True						,  lowercase_	: List[str]=True						,  lowercase_	: int="relu"						,  lowercase_	: List[Any]=3						,  lowercase_	: List[Any]=None						,  lowercase_	: Union[str, Any]=["stage2", "stage3", "stage4"]						,  lowercase_	: Union[str, Any]=[2, 3, 4]						,  lowercase_	: List[str]=1						,  ):
     snake_case_				:  Tuple       =			parent
     snake_case_				:  Dict       =			batch_size
     snake_case_				:  Dict       =			image_size
     snake_case_				:  int       =			num_channels
     snake_case_				:  Optional[int]       =			embeddings_size
     snake_case_				:  Union[str, Any]       =			hidden_sizes
     snake_case_				:  Optional[Any]       =			depths
     snake_case_				:  Union[str, Any]       =			is_training
     snake_case_				:  int       =			use_labels
     snake_case_				:  int       =			hidden_act
     snake_case_				:  Tuple       =			num_labels
     snake_case_				:  str       =			scope
     snake_case_				:  str       =			len(lowercase_       )
     snake_case_				:  List[Any]       =			out_features
     snake_case_				:  int       =			out_indices
     snake_case_				:  Tuple       =			num_groups

 def 		_snake_case      (  self	: Any       ):
     snake_case_				:  Any       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

     snake_case_				:  Optional[Any]       =			None
     if self.use_labels:
         snake_case_				:  List[Any]       =			ids_tensor([self.batch_size]						,  self.num_labels       )

     snake_case_				:  Optional[Any]       =			self.get_config()

     return config, pixel_values, labels

 def 		_snake_case      (  self	: int       ):
     return BitConfig(
         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						,  out_features=self.out_features						,  out_indices=self.out_indices						,  num_groups=self.num_groups						,  )

 def 		_snake_case      (  self	: Optional[int]						,  lowercase_	: str						,  lowercase_	: Tuple						,  lowercase_	: int       ):
     snake_case_				:  int       =			BitModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Any       =			model(lowercase_       )
     self.parent.assertEqual(
         result.last_hidden_state.shape						,  (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,  )

 def 		_snake_case      (  self	: List[str]						,  lowercase_	: Optional[Any]						,  lowercase_	: Optional[int]						,  lowercase_	: List[str]       ):
     snake_case_				:  Any       =			self.num_labels
     snake_case_				:  List[Any]       =			BitForImageClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Optional[Any]       =			model(lowercase_						,  labels=lowercase_       )
     self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)       )

 def 		_snake_case      (  self	: Optional[Any]						,  lowercase_	: Dict						,  lowercase_	: Optional[Any]						,  lowercase_	: List[Any]       ):
     snake_case_				:  Union[str, Any]       =			BitBackbone(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Dict       =			model(lowercase_       )

     # verify feature maps
     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
     snake_case_				:  Dict       =			None
     snake_case_				:  Union[str, Any]       =			BitBackbone(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  str       =			model(lowercase_       )

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





@require_torch
class  _UpperCAmelCase (    lowerCAmelCase__					,  lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    Union[str, Any]	      =	(BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
 _lowerCAmelCase     :    Dict	      =	(
     {"""feature-extraction""": BitModel, """image-classification""": BitForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCAmelCase     :    Tuple	      =	False
 _lowerCAmelCase     :    str	      =	False
 _lowerCAmelCase     :    int	      =	False
 _lowerCAmelCase     :    str	      =	False
 _lowerCAmelCase     :    Tuple	      =	False

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  Dict       =			BitModelTester(self       )
     snake_case_				:  int       =			ConfigTester(self						,  config_class=lowercase_						,  has_text_modality=lowercase_       )

 def 		_snake_case      (  self	: Tuple       ):
     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 		_snake_case      (  self	: Optional[Any]       ):
     return

 @unittest.skip(reason='''Bit does not output attentions'''       )
 def 		_snake_case      (  self	: int       ):
     pass

 @unittest.skip(reason='''Bit does not use inputs_embeds'''       )
 def 		_snake_case      (  self	: Optional[Any]       ):
     pass

 @unittest.skip(reason='''Bit does not support input and output embeddings'''       )
 def 		_snake_case      (  self	: List[Any]       ):
     pass

 def 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  List[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()

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

         snake_case_				:  List[Any]       =			['''pixel_values''']
         self.assertListEqual(arg_names[:1]						,  lowercase_       )

 def 		_snake_case      (  self	: List[Any]       ):
     snake_case_				:  Any       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )

 def 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  Dict       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowercase_       )

 def 		_snake_case      (  self	: str       ):
     snake_case_				:  int       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Tuple       =			model_class(config=lowercase_       )
         for name, module in model.named_modules():
             if isinstance(lowercase_						,  (nn.BatchNormad, nn.GroupNorm)       ):
                 self.assertTrue(
                     torch.all(module.weight == 1       )						,  msg=f"Parameter {name} of model {model_class} seems not properly initialized"						,  )
                 self.assertTrue(
                     torch.all(module.bias == 0       )						,  msg=f"Parameter {name} of model {model_class} seems not properly initialized"						,  )

 def 		_snake_case      (  self	: Optional[Any]       ):
     def check_hidden_states_output(lowercase_	: Any						,  lowercase_	: Tuple						,  lowercase_	: Dict       ):
         snake_case_				:  Optional[Any]       =			model_class(lowercase_       )
         model.to(lowercase_       )
         model.eval()

         with torch.no_grad():
             snake_case_				:  Optional[int]       =			model(**self._prepare_for_class(lowercase_						,  lowercase_       )       )

         snake_case_				:  Optional[int]       =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         snake_case_				:  List[str]       =			self.model_tester.num_stages
         self.assertEqual(len(lowercase_       )						,  expected_num_stages + 1       )

         # Bit'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_				:  Optional[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()
     snake_case_				:  Tuple       =			['''preactivation''', '''bottleneck''']
     for model_class in self.all_model_classes:
         for layer_type in layers_type:
             snake_case_				:  Tuple       =			layer_type
             snake_case_				:  Any       =			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_				:  Tuple       =			True

             check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

 @unittest.skip(reason='''Bit does not use feedforward chunking'''       )
 def 		_snake_case      (  self	: Tuple       ):
     pass

 def 		_snake_case      (  self	: Optional[int]       ):
     snake_case_				:  Optional[int]       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_       )






 @slow
 def 		_snake_case      (  self	: Any       ):
     for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_				:  Optional[int]       =			BitModel.from_pretrained(lowercase_       )
         self.assertIsNotNone(lowercase_       )





def __lowercase    (							):
    snake_case_				:  Any       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
    return image




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

 @cached_property
 def 		_snake_case      (  self	: Tuple       ):
     return (
         BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ) if is_vision_available() else None
     )






 @slow
 def 		_snake_case      (  self	: Optional[Any]       ):
     snake_case_				:  Optional[Any]       =			BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(lowercase_       )

     snake_case_				:  List[str]       =			self.default_image_processor
     snake_case_				:  Dict       =			prepare_img()
     snake_case_				:  str       =			image_processor(images=lowercase_						,  return_tensors='''pt'''       ).to(lowercase_       )

     # forward pass
     with torch.no_grad():
         snake_case_				:  Any       =			model(**lowercase_       )

     # verify the logits
     snake_case_				:  str       =			torch.Size((1, 1000)       )
     self.assertEqual(outputs.logits.shape						,  lowercase_       )

     snake_case_				:  List[Any]       =			torch.tensor([[-0.65_26, -0.52_63, -1.43_98]]       ).to(lowercase_       )

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





@require_torch
class  _UpperCAmelCase (    lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    Union[str, Any]	      =	(BitBackbone,) if is_torch_available() else ()
 _lowerCAmelCase     :    Tuple	      =	BitConfig

 _lowerCAmelCase     :    Any	      =	False

 def 		_snake_case      (  self	: Any       ):
     snake_case_				:  Union[str, Any]       =			BitModelTester(self       )










"""simple docstring"""

import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
     import torch_xla.core.xla_model as xm
     import torch_xla.debug.metrics as met




class  _UpperCAmelCase (    lowerCAmelCase__):

 def __init__(  self	: List[Any]						,  *lowercase_	: List[Any]						,  lowercase_	: Optional[Any]=None						,  lowercase_	: Tuple=None						,  **lowercase_	: Union[str, Any]       ):
     super().__init__(*lowercase_						,  **lowercase_       )
     snake_case_				:  str       =			eval_examples
     snake_case_				:  Optional[Any]       =			post_process_function

 def 		_snake_case      (  self	: Union[str, Any]						,  lowercase_	: Optional[Dataset] = None						,  lowercase_	: str=None						,  lowercase_	: Optional[List[str]] = None						,  lowercase_	: str = "eval"						,  **lowercase_	: Dict						,  ):
     snake_case_				:  int       =			gen_kwargs.copy()
     snake_case_				:  Dict       =			(
         gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''       ) is not None else self.args.generation_max_length
     )
     snake_case_				:  Tuple       =			(
         gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''       ) is not None else self.args.generation_num_beams
     )
     snake_case_				:  Optional[Any]       =			gen_kwargs

     snake_case_				:  Optional[int]       =			self.eval_dataset if eval_dataset is None else eval_dataset
     snake_case_				:  Optional[Any]       =			self.get_eval_dataloader(lowercase_       )
     snake_case_				:  Dict       =			self.eval_examples if eval_examples is None else eval_examples

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_				:  Optional[int]       =			self.compute_metrics
     snake_case_				:  str       =			None
     snake_case_				:  int       =			time.time()
     snake_case_				:  Any       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
         snake_case_				:  str       =			eval_loop(
             lowercase_						,  description='''Evaluation'''						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase_						,  metric_key_prefix=lowercase_						,  )
     finally:
         snake_case_				:  Optional[int]       =			compute_metrics
     snake_case_				:  Dict       =			self.args.eval_batch_size * self.args.world_size
     if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
         start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
     output.metrics.update(
         speed_metrics(
             lowercase_						,  lowercase_						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size       )						,  )       )

     if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
         # Only the main node write the results by default
         snake_case_				:  Tuple       =			self.post_process_function(lowercase_						,  lowercase_						,  lowercase_       )
         snake_case_				:  Optional[int]       =			self.compute_metrics(lowercase_       )

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()       ):
             if not key.startswith(f"{metric_key_prefix}_"       ):
                 snake_case_				:  int       =			metrics.pop(lowercase_       )

         metrics.update(output.metrics       )
     else:
         snake_case_				:  Tuple       =			output.metrics

     if self.args.should_log:
         # Only the main node log the results by default
         self.log(lowercase_       )

     if self.args.tpu_metrics_debug or self.args.debug:
         # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
         xm.master_print(met.metrics_report()       )

     snake_case_				:  str       =			self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  lowercase_       )
     return metrics






 def 		_snake_case      (  self	: Any						,  lowercase_	: int						,  lowercase_	: List[str]						,  lowercase_	: str=None						,  lowercase_	: str = "test"						,  **lowercase_	: Dict       ):
     snake_case_				:  Dict       =			gen_kwargs.copy()

     snake_case_				:  Dict       =			self.get_test_dataloader(lowercase_       )

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_				:  Tuple       =			self.compute_metrics
     snake_case_				:  int       =			None
     snake_case_				:  List[Any]       =			time.time()
     snake_case_				:  int       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
         snake_case_				:  List[str]       =			eval_loop(
             lowercase_						,  description='''Prediction'''						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase_						,  metric_key_prefix=lowercase_						,  )
     finally:
         snake_case_				:  str       =			compute_metrics

     snake_case_				:  int       =			self.args.eval_batch_size * self.args.world_size
     if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
         start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
     output.metrics.update(
         speed_metrics(
             lowercase_						,  lowercase_						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size       )						,  )       )
     if self.post_process_function is None or self.compute_metrics is None:
         return output

     snake_case_				:  Tuple       =			self.post_process_function(lowercase_						,  lowercase_						,  lowercase_						,  '''predict'''       )
     snake_case_				:  Dict       =			self.compute_metrics(lowercase_       )

     # Prefix all keys with metric_key_prefix + '_'
     for key in list(metrics.keys()       ):
         if not key.startswith(f"{metric_key_prefix}_"       ):
             snake_case_				:  Union[str, Any]       =			metrics.pop(lowercase_       )
     metrics.update(output.metrics       )
     return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=lowercase_       )





