
# 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(4_2)

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

__lowerCAmelCase					   =       'zero2'
__lowerCAmelCase					   =       'zero3'
__lowerCAmelCase					   =       [ZEROa, ZEROa]


def    a      ( a		,						a		,						a	)     ->Dict:




			'''simple docstring'''


			SCREAMING_SNAKE_CASE     						= parameterized.to_safe_name('''_'''.join(str(a	) 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     lowerCamelCase      (       __lowerCamelCase					):







	@parameterized.expand(lowercase   ,     name_func=lowercase			)
	def  snake_case__     (     self      :Optional[Any]   ,     lowercase      :str   ,     lowercase      :Dict			)		->      Optional[Any]:







				"""simple docstring"""






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







	@require_torch_multi_gpu
	@parameterized.expand(lowercase   ,     name_func=lowercase			)
	def  snake_case__     (     self      :Any   ,     lowercase      :Tuple   ,     lowercase      :int			)		->      List[Any]:







				"""simple docstring"""






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







	@parameterized.expand(lowercase   ,     name_func=lowercase			)
	def  snake_case__     (     self      :Dict   ,     lowercase      :List[Any]   ,     lowercase      :List[Any]			)		->      List[Any]:







				"""simple docstring"""






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







	@require_torch_multi_gpu
	@parameterized.expand(lowercase   ,     name_func=lowercase			)
	def  snake_case__     (     self      :Optional[Any]   ,     lowercase      :Tuple   ,     lowercase      :List[Any]			)		->      Any:







				"""simple docstring"""






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







	def  snake_case__     (     self      :int   ,     lowercase      :int			)		->      Optional[Any]:







				"""simple docstring"""






				pass







	def  snake_case__     (     self      :Optional[Any]   ,     lowercase      :str   ,     lowercase      :str   ,     lowercase      :int = 1_0   ,     lowercase      :bool = True   ,     lowercase      :bool = True   ,     lowercase      :bool = True   ,     )		->      Union[str, Any]:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= models[model]

				SCREAMING_SNAKE_CASE     						= self.run_trainer(
				    stage=lowercase   ,     model_name=lowercase   ,     eval_steps=lowercase   ,     num_train_epochs=1   ,     distributed=lowercase   ,     fpaa=lowercase   ,     )

				self.do_checks(lowercase			)

				return output_dir







	def  snake_case__     (     self      :Optional[int]   ,     lowercase      :str   ,     lowercase      :str   ,     lowercase      :int = 1_0   ,     lowercase      :int = 1   ,     lowercase      :bool = True   ,     lowercase      :bool = True   ,     )		->      str:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= self.get_auto_remove_tmp_dir('''./xxx'''   ,     after=lowercase			)
				SCREAMING_SNAKE_CASE     						= 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(lowercase			)}
            --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
				SCREAMING_SNAKE_CASE     						= f"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
				SCREAMING_SNAKE_CASE     						= [f"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
				SCREAMING_SNAKE_CASE     						= self.get_launcher(lowercase			)

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

				return output_dir







	def  snake_case__     (     self      :Tuple   ,     lowercase      :List[Any]=False			)		->      Optional[int]:







				"""simple docstring"""






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

import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin





class     lowerCamelCase      (       __lowerCamelCase ,		__lowerCamelCase					):







	@register_to_config
	def __init__(     self      :Tuple   ,     *,
	    lowercase      :int = 4   ,     lowercase      :int = 7_6_8   ,     lowercase      :int   ,     lowercase      :Any   ,     )		->      Optional[Any]:







				"""simple docstring"""






				super().__init__()

				SCREAMING_SNAKE_CASE     						= nn.Parameter(torch.zeros(lowercase			)			)

				# parameters for additional clip time embeddings
				SCREAMING_SNAKE_CASE     						= nn.Linear(lowercase   ,     lowercase			)
				SCREAMING_SNAKE_CASE     						= nn.Linear(lowercase   ,     lowercase			)

				# parameters for encoder hidden states
				SCREAMING_SNAKE_CASE     						= clip_extra_context_tokens
				SCREAMING_SNAKE_CASE     						= nn.Linear(
				    lowercase   ,     self.clip_extra_context_tokens * cross_attention_dim			)
				SCREAMING_SNAKE_CASE     						= nn.Linear(lowercase   ,     lowercase			)
				SCREAMING_SNAKE_CASE     						= nn.LayerNorm(lowercase			)







	def  snake_case__     (     self      :Union[str, Any]   ,     *, lowercase      :Optional[int]   ,     lowercase      :Union[str, Any]   ,     lowercase      :Union[str, Any]   ,     lowercase      :Optional[Any]			)		->      Union[str, Any]:







				"""simple docstring"""






				if do_classifier_free_guidance:
							# Add the classifier free guidance embeddings to the image embeddings
							SCREAMING_SNAKE_CASE     						= image_embeddings.shape[0]
							SCREAMING_SNAKE_CASE     						= self.learned_classifier_free_guidance_embeddings.unsqueeze(0			)
							SCREAMING_SNAKE_CASE     						= classifier_free_guidance_embeddings.expand(
							    lowercase   ,     -1			)
							SCREAMING_SNAKE_CASE     						= torch.cat([classifier_free_guidance_embeddings, image_embeddings]   ,     dim=0			)

				# The image embeddings batch size and the text embeddings batch size are equal
				assert image_embeddings.shape[0] == prompt_embeds.shape[0]

				SCREAMING_SNAKE_CASE     						= prompt_embeds.shape[0]

				# "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
				# adding CLIP embeddings to the existing timestep embedding, ...
				SCREAMING_SNAKE_CASE     						= self.embedding_proj(lowercase			)
				SCREAMING_SNAKE_CASE     						= self.clip_image_embeddings_project_to_time_embeddings(lowercase			)
				SCREAMING_SNAKE_CASE     						= time_projected_image_embeddings + time_projected_prompt_embeds

				# ... and by projecting CLIP embeddings into four
				# extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
				SCREAMING_SNAKE_CASE     						= self.clip_extra_context_tokens_proj(lowercase			)
				SCREAMING_SNAKE_CASE     						= clip_extra_context_tokens.reshape(lowercase   ,     -1   ,     self.clip_extra_context_tokens			)
				SCREAMING_SNAKE_CASE     						= clip_extra_context_tokens.permute(0   ,     2   ,     1			)

				SCREAMING_SNAKE_CASE     						= self.encoder_hidden_states_proj(lowercase			)
				SCREAMING_SNAKE_CASE     						= self.text_encoder_hidden_states_norm(lowercase			)
				SCREAMING_SNAKE_CASE     						= torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]   ,     dim=1			)

				return text_encoder_hidden_states, additive_clip_time_embeddings