





'''simple docstring'''




import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
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_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 SwiftFormerForImageClassification, SwiftFormerModel
    from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor






class UpperCAmelCase				:



    def __init__(	self  ,      __A  ,      __A=13  ,      __A=3  ,      __A=True  ,      __A=True  ,      __A=0.1  ,      __A=0.1  ,      __A=224  ,      __A=1_000  ,      __A=[3, 3, 6, 4]  ,      __A=[48, 56, 112, 220]  ,      ):
     __UpperCAmelCase       = parent
     __UpperCAmelCase       = batch_size
     __UpperCAmelCase       = num_channels
     __UpperCAmelCase       = is_training
     __UpperCAmelCase       = use_labels
     __UpperCAmelCase       = hidden_dropout_prob
     __UpperCAmelCase       = attention_probs_dropout_prob
     __UpperCAmelCase       = num_labels
     __UpperCAmelCase       = image_size
     __UpperCAmelCase       = layer_depths
     __UpperCAmelCase       = embed_dims



    def        __lowerCamelCase    (	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.num_labels       )

     __UpperCAmelCase       = self.get_config()

     return config, pixel_values, labels



    def        __lowerCamelCase    (	self       ):
     return SwiftFormerConfig(
         depths=self.layer_depths  ,      embed_dims=self.embed_dims  ,      mlp_ratio=4  ,      downsamples=[True, True, True, True]  ,      hidden_act='gelu'  ,      num_labels=self.num_labels  ,      down_patch_size=3  ,      down_stride=2  ,      down_pad=1  ,      drop_rate=0.0  ,      drop_path_rate=0.0  ,      use_layer_scale=__A  ,      layer_scale_init_value=1E-5  ,      )



    def        __lowerCamelCase    (	self  ,      __A  ,      __A  ,      __A       ):
     __UpperCAmelCase       = SwiftFormerModel(config=__A       )
     model.to(__A       )
     model.eval()
     __UpperCAmelCase       = model(__A       )
     self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, self.embed_dims[-1], 7, 7)       )



    def        __lowerCamelCase    (	self  ,      __A  ,      __A  ,      __A       ):
     __UpperCAmelCase       = self.num_labels
     __UpperCAmelCase       = SwiftFormerForImageClassification(__A       )
     model.to(__A       )
     model.eval()
     __UpperCAmelCase       = model(__A  ,      labels=__A       )
     self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )

     __UpperCAmelCase       = SwiftFormerForImageClassification(__A       )
     model.to(__A       )
     model.eval()

     __UpperCAmelCase       = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )
     __UpperCAmelCase       = model(__A       )
     self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )




    def        __lowerCamelCase    (	self       ):
     ((__UpperCAmelCase)       ,     (__UpperCAmelCase)       ,     (__UpperCAmelCase))       = self.prepare_config_and_inputs()
     __UpperCAmelCase       = {'pixel_values': pixel_values}
     return config, inputs_dict






@require_torch
class UpperCAmelCase				(		__A       ,      __A       ,      unittest.TestCase				):
    _A			:      Any     =							(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
    _A			:      List[str]     =							(
        {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification}
        if is_torch_available()
        else {}
    )

    _A			:      List[Any]     =							False
    _A			:      Union[str, Any]     =							False
    _A			:      int     =							False
    _A			:      str     =							False
    _A			:      Dict     =							False



    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       = SwiftFormerModelTester(self       )
     __UpperCAmelCase       = ConfigTester(
         self  ,      config_class=__A  ,      has_text_modality=__A  ,      hidden_size=37  ,      num_attention_heads=12  ,      num_hidden_layers=12  ,      )



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



    @unittest.skip(reason='SwiftFormer does not use inputs_embeds'       )
    def        __lowerCamelCase    (	self       ):
     pass



    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       ,     __UpperCAmelCase       = self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      __UpperCAmelCase       = model_class(__A       )
      __UpperCAmelCase       = model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(__A  ,      nn.Linear       )       )



    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       ,     __UpperCAmelCase       = self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      __UpperCAmelCase       = model_class(__A       )
      __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]  ,      __A       )



    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__A       )



    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__A       )



    @slow
    def        __lowerCamelCase    (	self       ):
     for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __UpperCAmelCase       = SwiftFormerModel.from_pretrained(__A       )
      self.assertIsNotNone(__A       )



    @unittest.skip(reason='SwiftFormer does not output attentions'       )
    def        __lowerCamelCase    (	self       ):
     pass



    def        __lowerCamelCase    (	self       ):
     def check_hidden_states_output(__A  ,      __A  ,      __A       ):
      __UpperCAmelCase       = model_class(__A       )
      model.to(__A       )
      model.eval()

      with torch.no_grad():
       __UpperCAmelCase       = model(**self._prepare_for_class(__A  ,      __A       )       )

      __UpperCAmelCase       = outputs.hidden_states

      __UpperCAmelCase       = 8
      self.assertEqual(len(__A       )  ,      __A       )  # TODO

      # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
      # with the width and height being successively divided by 2, after every 2 blocks
      for i in range(len(__A       )       ):
       self.assertEqual(
           hidden_states[i].shape  ,      torch.Size(
               [
                   self.model_tester.batch_size,
                   self.model_tester.embed_dims[i // 2],
                   (self.model_tester.image_size // 4) // 2 ** (i // 2),
                   (self.model_tester.image_size // 4) // 2 ** (i // 2),
               ]       )  ,      )

     __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(__A  ,      __A  ,      __A       )

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

      check_hidden_states_output(__A  ,      __A  ,      __A       )



    def        __lowerCamelCase    (	self       ):
     def _config_zero_init(__A       ):
      __UpperCAmelCase       = copy.deepcopy(__A       )
      for key in configs_no_init.__dict__.keys():
       if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
        setattr(__A  ,      __A  ,      1E-10       )
       if isinstance(getattr(__A  ,      __A  ,      __A       )  ,      __A       ):
        __UpperCAmelCase       = _config_zero_init(getattr(__A  ,      __A       )       )
        setattr(__A  ,      __A  ,      __A       )
      return configs_no_init

     __UpperCAmelCase       ,     __UpperCAmelCase       = self.model_tester.prepare_config_and_inputs_for_common()

     __UpperCAmelCase       = _config_zero_init(__A       )
     for model_class in self.all_model_classes:
      __UpperCAmelCase       = model_class(config=__A       )
      for name, param in model.named_parameters():
       if param.requires_grad:
        self.assertIn(
            ((param.data.mean() * 1E9) / 1E9).round().item()  ,      [0.0, 1.0]  ,      msg=f'Parameter {name} of model {model_class} seems not properly initialized'  ,      )




    @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
    def        __lowerCamelCase    (	self       ):
     pass







def _lowerCAmelCase  (   )->  Optional[Any]:
 __UpperCAmelCase       = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
 return image






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



    @cached_property
    def        __lowerCamelCase    (	self       ):
     return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs'       ) if is_vision_available() else None




    @slow
    def        __lowerCamelCase    (	self       ):
     __UpperCAmelCase       = SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs'       ).to(__A       )

     __UpperCAmelCase       = self.default_image_processor
     __UpperCAmelCase       = prepare_img()
     __UpperCAmelCase       = image_processor(images=__A  ,      return_tensors='pt'       ).to(__A       )

     # forward pass
     with torch.no_grad():
      __UpperCAmelCase       = model(**__A       )

     # verify the logits
     __UpperCAmelCase       = torch.Size((1, 1_000)       )
     self.assertEqual(outputs.logits.shape  ,      __A       )

     __UpperCAmelCase       = torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]]       ).to(__A       )
     self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,      __A  ,      atol=1E-4       )       )









import comet  # From: unbabel-comet
import torch

import datasets


SCREAMING_SNAKE_CASE							    =							datasets.logging.get_logger(__name__)

SCREAMING_SNAKE_CASE							    =							'\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = "{COMET}: A Neural Framework for {MT} Evaluation",\n   author = "Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon",\n   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n   month = nov,\n   year = "2020",\n   address = "Online",\n   publisher = "Association for Computational Linguistics",\n   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n   pages = "2685--2702",\n}\n'

SCREAMING_SNAKE_CASE							    =							'\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

SCREAMING_SNAKE_CASE							    =							'\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,					_KWARGS_DESCRIPTION							)
class     __UpperCAmelCase							(       datasets.Metric							):


     """simple docstring"""


     def 	snake_case_  (	self    ):
        return datasets.MetricInfo(
            description=_DESCRIPTION  ,       citation=_CITATION  ,       homepage="""https://unbabel.github.io/COMET/html/index.html"""  ,       inputs_description=_KWARGS_DESCRIPTION  ,       features=datasets.Features(
                {
                    """sources""": datasets.Value("""string"""  ,       id="""sequence"""    ),
                    """predictions""": datasets.Value("""string"""  ,       id="""sequence"""    ),
                    """references""": datasets.Value("""string"""  ,       id="""sequence"""    ),
                }    )  ,       codebase_urls=["""https://github.com/Unbabel/COMET"""]  ,       reference_urls=[
                """https://github.com/Unbabel/COMET""",
                """https://www.aclweb.org/anthology/2020.emnlp-main.213/""",
                """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""",
            ]  ,       )


     def 	snake_case_  (	self  ,       __A    ):
        if self.config_name == "default":
           __a					=  comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""    )    )
        else:
           __a					=  comet.load_from_checkpoint(comet.download_model(self.config_name    )    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A  ,       __A=None  ,       __A=False    ):
        if gpus is None:
           __a					=  1 if torch.cuda.is_available() else 0
        __a					=  {"""src""": sources, """mt""": predictions, """ref""": references}
        __a					=  [dict(zip(__A  ,       __A    )    ) for t in zip(*data.values()    )]
        __a	,    __a					=  self.scorer.predict(__A  ,       gpus=__A  ,       progress_bar=__A    )
        return {"mean_score": mean_score, "scores": scores}



