

# 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


__a    :Tuple      =			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)

__a    :int      =			{'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'}

__a    :List[str]      =			'zero2'
__a    :Dict      =			'zero3'
__a    :List[str]      =			[ZEROa, ZEROa]

def       __snake_case						( __UpperCamelCase	: Optional[Any]				,__UpperCamelCase	: Dict				,__UpperCamelCase	: Tuple    ):



      """simple docstring"""

      A_						  =				parameterized.to_safe_name("_".join(str(__UpperCamelCase    ) for x in param.args    )    )
      return f'''{func.__name__}_{param_based_name}'''


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



@slow
@require_deepspeed
@require_torch_gpu
class   _a					(			snake_case_				):




      """simple docstring"""

      @parameterized.expand(UpperCAmelCase						,			name_func=UpperCAmelCase	)
      def 		__A	(   self							:				List[str]						,			UpperCAmelCase							:				int						,			UpperCAmelCase							:				List[Any]	):
            self.run_and_check(
                stage=UpperCAmelCase						,			model=UpperCAmelCase						,			distributed=UpperCAmelCase						,			fpaa=UpperCAmelCase						,			)





      @require_torch_multi_gpu
      @parameterized.expand(UpperCAmelCase						,			name_func=UpperCAmelCase	)
      def 		__A	(   self							:				Optional[int]						,			UpperCAmelCase							:				List[Any]						,			UpperCAmelCase							:				Union[str, Any]	):
            self.run_and_check(
                stage=UpperCAmelCase						,			model=UpperCAmelCase						,			distributed=UpperCAmelCase						,			fpaa=UpperCAmelCase						,			)





      @parameterized.expand(UpperCAmelCase						,			name_func=UpperCAmelCase	)
      def 		__A	(   self							:				List[Any]						,			UpperCAmelCase							:				Optional[Any]						,			UpperCAmelCase							:				Dict	):
            self.run_and_check(
                stage=UpperCAmelCase						,			model=UpperCAmelCase						,			distributed=UpperCAmelCase						,			fpaa=UpperCAmelCase						,			)





      @require_torch_multi_gpu
      @parameterized.expand(UpperCAmelCase						,			name_func=UpperCAmelCase	)
      def 		__A	(   self							:				Union[str, Any]						,			UpperCAmelCase							:				Optional[int]						,			UpperCAmelCase							:				Union[str, Any]	):
            self.run_and_check(
                stage=UpperCAmelCase						,			model=UpperCAmelCase						,			distributed=UpperCAmelCase						,			fpaa=UpperCAmelCase						,			)





      def 		__A	(   self							:				Union[str, Any]						,			UpperCAmelCase							:				Any	):
            # XXX: run_asr is premature and doesn't save any results
            # so all we check for now is that the process didn't fail
            pass





      def 		__A	(   self							:				Optional[int]						,			UpperCAmelCase							:				str						,			UpperCAmelCase							:				str						,			UpperCAmelCase							:				int = 10						,			UpperCAmelCase							:				bool = True						,			UpperCAmelCase							:				bool = True						,			UpperCAmelCase							:				bool = True						,			):
            A_						  =				models[model]

            A_						  =				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 		__A	(   self							:				Union[str, Any]						,			UpperCAmelCase							:				str						,			UpperCAmelCase							:				str						,			UpperCAmelCase							:				int = 10						,			UpperCAmelCase							:				int = 1						,			UpperCAmelCase							:				bool = True						,			UpperCAmelCase							:				bool = True						,			):
            A_						  =				self.get_auto_remove_tmp_dir("./xxx"						,			after=UpperCAmelCase	)
            A_						  =				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
            A_						  =				f'''--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'''.split()
            A_						  =				[f'''{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py''']
            A_						  =				self.get_launcher(UpperCAmelCase	)

            A_						  =				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 		__A	(   self							:				Dict						,			UpperCAmelCase							:				Optional[int]=False	):
            # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
            # - it won't be able to handle that
            # 2. for now testing with just 2 gpus max (since some quality tests may give different
            # results with mode gpus because we use very little data)
            A_						  =				min(2						,			get_gpu_count()	) if distributed else 1
            return f'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()


'''simple docstring'''







import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class        A__   (   _snake_case      ):
    lowercase						       =		["image_processor", "tokenizer"]
    lowercase						       =		"OwlViTImageProcessor"
    lowercase						       =		("CLIPTokenizer", "CLIPTokenizerFast")



    def __init__(       self		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					**UpperCamelCase__							)    ->   str:





           '''simple docstring'''
           A_						       =   None
           if "feature_extractor" in kwargs:
                  warnings.warn(
                      """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                      """ instead."""		,					UpperCamelCase__		,					)
                  A_						       =   kwargs.pop("""feature_extractor"""							)

           A_						       =   image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
                  raise ValueError("""You need to specify an `image_processor`."""							)
           if tokenizer is None:
                  raise ValueError("""You need to specify a `tokenizer`."""							)

           super().__init__(UpperCamelCase__		,					UpperCamelCase__							)



    def __call__(       self		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__="max_length"		,					UpperCamelCase__="np"		,					**UpperCamelCase__							)    ->   int:





           '''simple docstring'''

           if text is None and query_images is None and images is None:
                  raise ValueError(
                      """You have to specify at least one text or query image or image. All three cannot be none."""							)

           if text is not None:
                  if isinstance(UpperCamelCase__		,					UpperCamelCase__							) or (isinstance(UpperCamelCase__		,					UpperCamelCase__							) and not isinstance(text[0]		,					UpperCamelCase__							)):
                         A_						       =   [self.tokenizer(UpperCamelCase__		,					padding=UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)]

                  elif isinstance(UpperCamelCase__		,					UpperCamelCase__							) and isinstance(text[0]		,					UpperCamelCase__							):
                         A_						       =   []

                         # Maximum number of queries across batch
                         A_						       =   max([len(UpperCamelCase__							) for t in text]							)

                         # Pad all batch samples to max number of text queries
                         for t in text:
                                if len(UpperCamelCase__							) != max_num_queries:
                                       A_						       =   t + [""" """] * (max_num_queries - len(UpperCamelCase__							))

                                A_						       =   self.tokenizer(UpperCamelCase__		,					padding=UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)
                                encodings.append(UpperCamelCase__							)
                  else:
                         raise TypeError("""Input text should be a string, a list of strings or a nested list of strings"""							)

                  if return_tensors == "np":
                         A_						       =   np.concatenate([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   np.concatenate([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  elif return_tensors == "jax" and is_flax_available():
                         import jax.numpy as jnp

                         A_						       =   jnp.concatenate([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  elif return_tensors == "pt" and is_torch_available():
                         import torch

                         A_						       =   torch.cat([encoding["""input_ids"""] for encoding in encodings]		,					dim=0							)
                         A_						       =   torch.cat([encoding["""attention_mask"""] for encoding in encodings]		,					dim=0							)

                  elif return_tensors == "tf" and is_tf_available():
                         import tensorflow as tf

                         A_						       =   tf.stack([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   tf.stack([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  else:
                         raise ValueError("""Target return tensor type could not be returned"""							)

                  A_						       =   BatchEncoding()
                  A_						       =   input_ids
                  A_						       =   attention_mask

           if query_images is not None:
                  A_						       =   BatchEncoding()
                  A_						       =   self.image_processor(
                      UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							).pixel_values
                  A_						       =   query_pixel_values

           if images is not None:
                  A_						       =   self.image_processor(UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)

           if text is not None and images is not None:
                  A_						       =   image_features.pixel_values
                  return encoding
           elif query_images is not None and images is not None:
                  A_						       =   image_features.pixel_values
                  return encoding
           elif text is not None or query_images is not None:
                  return encoding
           else:
                  return BatchEncoding(data=dict(**UpperCamelCase__							)		,					tensor_type=UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           return self.image_processor.post_process(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   List[Any]:





           '''simple docstring'''
           return self.image_processor.post_process_object_detection(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   Tuple:





           '''simple docstring'''
           return self.image_processor.post_process_image_guided_detection(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   Any:





           '''simple docstring'''
           return self.tokenizer.batch_decode(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   List[str]:





           '''simple docstring'''
           return self.tokenizer.decode(*UpperCamelCase__		,					**UpperCamelCase__							)



    @property
    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           warnings.warn(
               """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""		,					UpperCamelCase__		,					)
           return self.image_processor_class







    @property
    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           warnings.warn(
               """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""		,					UpperCamelCase__		,					)
           return self.image_processor
