


import json
import logging
import os
import sys
from pathlib import Path

import finetune_rag

from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    require_ray,
    require_torch_gpu,
    require_torch_multi_gpu,
)


logging.basicConfig(level=logging.DEBUG)
SCREAMING_SNAKE_CASE_      =			logging.getLogger()

SCREAMING_SNAKE_CASE_      =			logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)


class  lowerCAmelCase_						(       snake_case__      ):





  """simple docstring"""



  def __a						(					self     :							Union[str, Any]				,							SCREAMING_SNAKE_CASE__     :							List[str]						):





       '''simple docstring'''

       os.makedirs(SCREAMING_SNAKE_CASE__				,							exist_ok=SCREAMING_SNAKE_CASE__						)
       __a       =   {"""source""": """What is love ?""", """target""": """life"""}
       __a       =   {"""train""": 1_2, """val""": 2, """test""": 2}
       for split in ["train", "test", "val"]:
            for field in ["source", "target"]:
                 __a       =   """\n""".join([contents[field]] * n_lines[split]						)
                 with open(os.path.join(SCREAMING_SNAKE_CASE__				,							f'''{split}.{field}'''						)				,							"""w"""						) as f:
                      f.write(SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Dict				,							SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							str = "pytorch"						):





       '''simple docstring'''

       __a       =   self.get_auto_remove_tmp_dir()
       __a       =   os.path.join(SCREAMING_SNAKE_CASE__				,							"""output"""						)
       __a       =   os.path.join(SCREAMING_SNAKE_CASE__				,							"""data"""						)
       self._create_dummy_data(data_dir=SCREAMING_SNAKE_CASE__						)

       __a       =   f'''
                --data_dir {data_dir} \
                --output_dir {output_dir} \
                --model_name_or_path facebook/rag-sequence-base \
                --model_type rag_sequence \
                --do_train \
                --do_predict \
                --n_val -1 \
                --val_check_interval 1.0 \
                --train_batch_size 2 \
                --eval_batch_size 1 \
                --max_source_length 25 \
                --max_target_length 25 \
                --val_max_target_length 25 \
                --test_max_target_length 25 \
                --label_smoothing 0.1 \
                --dropout 0.1 \
                --attention_dropout 0.1 \
                --weight_decay 0.001 \
                --adam_epsilon 1e-08 \
                --max_grad_norm 0.1 \
                --lr_scheduler polynomial \
                --learning_rate 3e-04 \
                --num_train_epochs 1 \
                --warmup_steps 4 \
                --gradient_accumulation_steps 1 \
                --distributed-port 8787 \
                --use_dummy_dataset 1 \
                --distributed_retriever {distributed_retriever} \
            '''.split()

       if gpus > 0:
            testargs.append(f'''--gpus={gpus}'''						)
            if is_apex_available():
                 testargs.append("""--fp16"""						)
       else:
            testargs.append("""--gpus=0"""						)
            testargs.append("""--distributed_backend=ddp_cpu"""						)
            testargs.append("""--num_processes=2"""						)

       __a       =   [sys.executable, str(Path(finetune_rag.__file__						).resolve()						)] + testargs
       execute_subprocess_async(SCREAMING_SNAKE_CASE__				,							env=self.get_env()						)

       __a       =   os.path.join(SCREAMING_SNAKE_CASE__				,							"""metrics.json"""						)
       with open(SCREAMING_SNAKE_CASE__						) as f:
            __a       =   json.load(SCREAMING_SNAKE_CASE__						)
       return result

  @require_torch_gpu
  def __a						(					self     :							Tuple						):





       '''simple docstring'''

       __a       =   self._run_finetune(gpus=1						)
       self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]				,							0.2						)

  @require_torch_multi_gpu
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   self._run_finetune(gpus=2						)
       self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]				,							0.2						)

  @require_torch_gpu
  @require_ray
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   self._run_finetune(gpus=1				,							distributed_retriever="""ray"""						)
       self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]				,							0.2						)


  @require_torch_multi_gpu
  @require_ray
  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   self._run_finetune(gpus=1				,							distributed_retriever="""ray"""						)
       self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]				,							0.2						)










'''simple docstring'''







import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
 from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class  lowerCAmelCase_						:





  """simple docstring"""



  def __init__(					self     :							Any				,							SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							List[str]=1_3				,							SCREAMING_SNAKE_CASE__     :							int=3_0				,							SCREAMING_SNAKE_CASE__     :							List[str]=2				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=3				,							SCREAMING_SNAKE_CASE__     :							List[str]=True				,							SCREAMING_SNAKE_CASE__     :							Dict=True				,							SCREAMING_SNAKE_CASE__     :							str=3_2				,							SCREAMING_SNAKE_CASE__     :							Tuple=5				,							SCREAMING_SNAKE_CASE__     :							List[Any]=4				,							SCREAMING_SNAKE_CASE__     :							Dict=3_7				,							SCREAMING_SNAKE_CASE__     :							Any="gelu"				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]=0.1				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=0.1				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=1_0				,							SCREAMING_SNAKE_CASE__     :							str=0.0_2				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=None				,							SCREAMING_SNAKE_CASE__     :							Any=2				,							):





       '''simple docstring'''

       __a       =   parent
       __a       =   batch_size
       __a       =   image_size
       __a       =   patch_size
       __a       =   num_channels
       __a       =   is_training
       __a       =   use_labels
       __a       =   hidden_size
       __a       =   num_hidden_layers
       __a       =   num_attention_heads
       __a       =   intermediate_size
       __a       =   hidden_act
       __a       =   hidden_dropout_prob
       __a       =   attention_probs_dropout_prob
       __a       =   type_sequence_label_size
       __a       =   initializer_range
       __a       =   scope
       __a       =   encoder_stride

       # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       __a       =   (image_size // patch_size) ** 2
       __a       =   num_patches + 1

  def __a						(					self     :							Any						):





       '''simple docstring'''

       __a       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       __a       =   None
       if self.use_labels:
            __a       =   ids_tensor([self.batch_size]				,							self.type_sequence_label_size						)

       __a       =   self.get_config()

       return config, pixel_values, labels

  def __a						(					self     :							Optional[int]						):





       '''simple docstring'''

       return ViTConfig(
           image_size=self.image_size				,							patch_size=self.patch_size				,							num_channels=self.num_channels				,							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				,							is_decoder=SCREAMING_SNAKE_CASE__				,							initializer_range=self.initializer_range				,							encoder_stride=self.encoder_stride				,							)

  def __a						(					self     :							Dict				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]				,							SCREAMING_SNAKE_CASE__     :							Any				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   ViTModel(config=SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)						)

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							List[str]				,							SCREAMING_SNAKE_CASE__     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							str						):





       '''simple docstring'''

       __a       =   ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(
           result.reconstruction.shape				,							(self.batch_size, self.num_channels, self.image_size, self.image_size)						)

       # test greyscale images
       __a       =   1
       __a       =   ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()

       __a       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.reconstruction.shape				,							(self.batch_size, 1, self.image_size, self.image_size)						)

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							List[Any]				,							SCREAMING_SNAKE_CASE__     :							Dict						):





       '''simple docstring'''

       __a       =   self.type_sequence_label_size
       __a       =   ViTForImageClassification(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__				,							labels=SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)						)

       # test greyscale images
       __a       =   1
       __a       =   ViTForImageClassification(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()

       __a       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)						)


  def __a						(					self     :							str						):





       '''simple docstring'''

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


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





  """simple docstring"""



  a_       :str												=(
      (
          ViTModel,
          ViTForImageClassification,
          ViTForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  a_       :Tuple												=(
      {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
      if is_torch_available()
      else {}
  )
  a_       :List[str]												=True

  a_       :str												=False
  a_       :Optional[int]												=False
  a_       :Tuple												=False

  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   ViTModelTester(self						)
       __a       =   ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE__				,							has_text_modality=SCREAMING_SNAKE_CASE__				,							hidden_size=3_7						)

  def __a						(					self     :							Dict						):





       '''simple docstring'''

       self.config_tester.run_common_tests()

  @unittest.skip(reason="""ViT does not use inputs_embeds"""						)
  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       pass

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a ,						__a       =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            __a       =   model_class(SCREAMING_SNAKE_CASE__						)
            self.assertIsInstance(model.get_input_embeddings()				,							(nn.Module)						)
            __a       =   model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__				,							nn.Linear						)						)

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a ,						__a       =   self.model_tester.prepare_config_and_inputs_for_common()

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

            __a       =   ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]				,							SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Union[str, Any]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__						)


  @slow
  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a       =   ViTModel.from_pretrained(SCREAMING_SNAKE_CASE__						)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE__						)




def        __lowercase						(      )				->					int:
     """simple docstring"""




     __a       =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
     return image



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





  """simple docstring"""



  @cached_property
  def __a						(					self     :							str						):





       '''simple docstring'''

       return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""						) if is_vision_available() else None

  @slow
  def __a						(					self     :							Dict						):





       '''simple docstring'''

       __a       =   ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""						).to(SCREAMING_SNAKE_CASE__						)

       __a       =   self.default_image_processor
       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						).to(SCREAMING_SNAKE_CASE__						)

       # forward pass
       with torch.no_grad():
            __a       =   model(**SCREAMING_SNAKE_CASE__						)

       # verify the logits
       __a       =   torch.Size((1, 1_0_0_0)						)
       self.assertEqual(outputs.logits.shape				,							SCREAMING_SNAKE_CASE__						)

       __a       =   torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]						).to(SCREAMING_SNAKE_CASE__						)

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

  @slow
  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   ViTModel.from_pretrained("""facebook/dino-vits8"""						).to(SCREAMING_SNAKE_CASE__						)

       __a       =   ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""				,							size=4_8_0						)
       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						)
       __a       =   inputs.pixel_values.to(SCREAMING_SNAKE_CASE__						)

       # forward pass
       with torch.no_grad():
            __a       =   model(SCREAMING_SNAKE_CASE__				,							interpolate_pos_encoding=SCREAMING_SNAKE_CASE__						)

       # verify the logits
       __a       =   torch.Size((1, 3_6_0_1, 3_8_4)						)
       self.assertEqual(outputs.last_hidden_state.shape				,							SCREAMING_SNAKE_CASE__						)

       __a       =   torch.tensor(
           [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]]						).to(SCREAMING_SNAKE_CASE__						)

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


  @slow
  @require_accelerate
  @require_torch_gpu
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   ViTModel.from_pretrained("""facebook/dino-vits8"""				,							torch_dtype=torch.floataa				,							device_map="""auto"""						)
       __a       =   self.default_image_processor

       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						)
       __a       =   inputs.pixel_values.to(SCREAMING_SNAKE_CASE__						)

       # forward pass to make sure inference works in fp16
       with torch.no_grad():
            __a       =   model(SCREAMING_SNAKE_CASE__						)






