



"""simple docstring"""





import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import BeitImageProcessor
class 				lowercase__       (   unittest.TestCase				):







       '''simple docstring'''


       def __init__(							self      :  Union[str, Any]		,    _UpperCAmelCase      :  Dict		,    _UpperCAmelCase      :  Optional[int]=7		,    _UpperCAmelCase      :  List[str]=3		,    _UpperCAmelCase      :  List[Any]=18		,    _UpperCAmelCase      :  int=30		,    _UpperCAmelCase      :  List[Any]=400		,    _UpperCAmelCase      :  Union[str, Any]=True		,    _UpperCAmelCase      :  List[Any]=None		,    _UpperCAmelCase      :  List[Any]=True		,    _UpperCAmelCase      :  str=None		,    _UpperCAmelCase      :  Any=True		,    _UpperCAmelCase      :  Optional[int]=[0.5, 0.5, 0.5]		,    _UpperCAmelCase      :  Union[str, Any]=[0.5, 0.5, 0.5]		,    _UpperCAmelCase      :  List[str]=False		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							size if size is not None else {"height": 20, "width": 20}
             UpperCAmelCase_      			=							crop_size if crop_size is not None else {"height": 18, "width": 18}
             UpperCAmelCase_      			=							parent
             UpperCAmelCase_      			=							batch_size
             UpperCAmelCase_      			=							num_channels
             UpperCAmelCase_      			=							image_size
             UpperCAmelCase_      			=							min_resolution
             UpperCAmelCase_      			=							max_resolution
             UpperCAmelCase_      			=							do_resize
             UpperCAmelCase_      			=							size
             UpperCAmelCase_      			=							do_center_crop
             UpperCAmelCase_      			=							crop_size
             UpperCAmelCase_      			=							do_normalize
             UpperCAmelCase_      			=							image_mean
             UpperCAmelCase_      			=							image_std
             UpperCAmelCase_      			=							do_reduce_labels







       def 					lowercase__    (							self      :  Optional[Any]   )			->						Optional[int]:


             '''simple docstring'''




             return {
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "do_center_crop": self.do_center_crop,
                 "crop_size": self.crop_size,
                 "do_normalize": self.do_normalize,
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
                 "do_reduce_labels": self.do_reduce_labels,
             }



def        a__     (				):
      UpperCAmelCase_      			=							load_dataset("hf-internal-testing/fixtures_ade20k"     ,      split="test"				)

      UpperCAmelCase_      			=							Image.open(dataset[0]["file"]				)
      UpperCAmelCase_      			=							Image.open(dataset[1]["file"]				)

      return image, map
def        a__     (				):
      UpperCAmelCase_      			=							load_dataset("hf-internal-testing/fixtures_ade20k"     ,      split="test"				)

      UpperCAmelCase_      			=							Image.open(ds[0]["file"]				)
      UpperCAmelCase_      			=							Image.open(ds[1]["file"]				)
      UpperCAmelCase_      			=							Image.open(ds[2]["file"]				)
      UpperCAmelCase_      			=							Image.open(ds[3]["file"]				)

      return [imagea, imagea], [mapa, mapa]


@require_torch
@require_vision
class 				lowercase__       (   SCREAMING_SNAKE_CASE    , unittest.TestCase				):







       '''simple docstring'''


       UpperCamelCase						=					BeitImageProcessor if is_vision_available() else None



       def 					lowercase__    (							self      :  Any   )			->						List[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							BeitImageProcessingTester(self   )



       @property
       def 					lowercase__    (							self      :  List[Any]   )			->						Dict:


             '''simple docstring'''




             return self.image_processor_tester.prepare_image_processor_dict()



       def 					lowercase__    (							self      :  Optional[int]   )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "do_resize"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "size"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "do_center_crop"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "center_crop"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "do_normalize"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "image_mean"   )   )
             self.assertTrue(hasattr(_UpperCAmelCase		,    "image_std"   )   )



       def 					lowercase__    (							self      :  List[str]   )			->						List[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class.from_dict(self.image_processor_dict   )
             self.assertEqual(image_processor.size		,    {"height": 20, "width": 20}   )
             self.assertEqual(image_processor.crop_size		,    {"height": 18, "width": 18}   )
             self.assertEqual(image_processor.do_reduce_labels		,    _UpperCAmelCase   )

             UpperCAmelCase_      			=							self.image_processing_class.from_dict(
                 self.image_processor_dict		,    size=42		,    crop_size=84		,    reduce_labels=_UpperCAmelCase   )
             self.assertEqual(image_processor.size		,    {"height": 42, "width": 42}   )
             self.assertEqual(image_processor.crop_size		,    {"height": 84, "width": 84}   )
             self.assertEqual(image_processor.do_reduce_labels		,    _UpperCAmelCase   )



       def 					lowercase__    (							self      :  Optional[int]   )			->						Dict:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  str   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )
             # create random PIL images
             UpperCAmelCase_      			=							prepare_image_inputs(self.image_processor_tester		,    equal_resolution=_UpperCAmelCase   )
             for image in image_inputs:
                   self.assertIsInstance(_UpperCAmelCase		,    Image.Image   )

             # Test not batched input
             UpperCAmelCase_      			=							image_processing(image_inputs[0]		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )

             # Test batched
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )



       def 					lowercase__    (							self      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )
             # create random numpy tensors
             UpperCAmelCase_      			=							prepare_image_inputs(self.image_processor_tester		,    equal_resolution=_UpperCAmelCase		,    numpify=_UpperCAmelCase   )
             for image in image_inputs:
                   self.assertIsInstance(_UpperCAmelCase		,    np.ndarray   )

             # Test not batched input
             UpperCAmelCase_      			=							image_processing(image_inputs[0]		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )

             # Test batched
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )



       def 					lowercase__    (							self      :  Tuple   )			->						Dict:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )
             # create random PyTorch tensors
             UpperCAmelCase_      			=							prepare_image_inputs(self.image_processor_tester		,    equal_resolution=_UpperCAmelCase		,    torchify=_UpperCAmelCase   )
             for image in image_inputs:
                   self.assertIsInstance(_UpperCAmelCase		,    torch.Tensor   )

             # Test not batched input
             UpperCAmelCase_      			=							image_processing(image_inputs[0]		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )

             # Test batched
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    return_tensors="pt"   ).pixel_values
             self.assertEqual(
                 encoded_images.shape		,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )



       def 					lowercase__    (							self      :  List[str]   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )
             # create random PyTorch tensors
             UpperCAmelCase_      			=							prepare_image_inputs(self.image_processor_tester		,    equal_resolution=_UpperCAmelCase		,    torchify=_UpperCAmelCase   )
             UpperCAmelCase_      			=							[]
             for image in image_inputs:
                   self.assertIsInstance(_UpperCAmelCase		,    torch.Tensor   )
                   maps.append(torch.zeros(image.shape[-2:]   ).long()   )

             # Test not batched input
             UpperCAmelCase_      			=							image_processing(image_inputs[0]		,    maps[0]		,    return_tensors="pt"   )
             self.assertEqual(
                 encoding["pixel_values"].shape		,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(
                 encoding["labels"].shape		,    (
                     1,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(encoding["labels"].dtype		,    torch.long   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 255   )

             # Test batched
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    _UpperCAmelCase		,    return_tensors="pt"   )
             self.assertEqual(
                 encoding["pixel_values"].shape		,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(
                 encoding["labels"].shape		,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(encoding["labels"].dtype		,    torch.long   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 255   )

             # Test not batched input (PIL images)
             UpperCAmelCase_			,   UpperCAmelCase_      			=							prepare_semantic_single_inputs()

             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    _UpperCAmelCase		,    return_tensors="pt"   )
             self.assertEqual(
                 encoding["pixel_values"].shape		,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(
                 encoding["labels"].shape		,    (
                     1,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(encoding["labels"].dtype		,    torch.long   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 255   )

             # Test batched input (PIL images)
             UpperCAmelCase_			,   UpperCAmelCase_      			=							prepare_semantic_batch_inputs()

             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    _UpperCAmelCase		,    return_tensors="pt"   )
             self.assertEqual(
                 encoding["pixel_values"].shape		,    (
                     2,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(
                 encoding["labels"].shape		,    (
                     2,
                     self.image_processor_tester.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )		,    )
             self.assertEqual(encoding["labels"].dtype		,    torch.long   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 255   )







       def 					lowercase__    (							self      :  List[Any]   )			->						Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.image_processing_class(**self.image_processor_dict   )

             # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
             UpperCAmelCase_			,   UpperCAmelCase_      			=							prepare_semantic_single_inputs()
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    _UpperCAmelCase		,    return_tensors="pt"   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 150   )

             UpperCAmelCase_      			=							True
             UpperCAmelCase_      			=							image_processing(_UpperCAmelCase		,    _UpperCAmelCase		,    return_tensors="pt"   )
             self.assertTrue(encoding["labels"].min().item() >= 0   )
             self.assertTrue(encoding["labels"].max().item() <= 255   )









"""simple docstring"""





# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


lowerCamelCase       	=						Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

lowerCamelCase       	=						{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCamelCase       	=						"""zero2"""
lowerCamelCase       	=						"""zero3"""
lowerCamelCase       	=						[ZEROa, ZEROa]
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # customize the test name generator function as we want both params to appear in the sub-test
      # name, as by default it shows only the first param
      UpperCAmelCase_      			=							parameterized.to_safe_name("_".join(str(lowerCAmelCase__				) for x in param.args				)				)
      return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
lowerCamelCase       	=						list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Any   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Union[str, Any]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  int		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[int]   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							self.run_trainer(
                 stage=_UpperCAmelCase		,    model_name=_UpperCAmelCase		,    eval_steps=_UpperCAmelCase		,    num_train_epochs=1		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )

             self.do_checks(_UpperCAmelCase   )

             return output_dir



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_auto_remove_tmp_dir("./xxx"		,    after=_UpperCAmelCase   )
             UpperCAmelCase_      			=							F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(_UpperCAmelCase   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

             if fpaa:
                   args.extend(["--fp16"]   )

             # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
             # hence the separate config files
             UpperCAmelCase_      			=							F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
             UpperCAmelCase_      			=							[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
             UpperCAmelCase_      			=							self.get_launcher(_UpperCAmelCase   )

             UpperCAmelCase_      			=							launcher + script + args + ds_args
             # keep for quick debug
             # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
             execute_subprocess_async(_UpperCAmelCase		,    env=self.get_env()   )

             return output_dir







       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							min(2		,    get_gpu_count()   ) if distributed else 1
             return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()




